Stream流中将集合转成map,重复key处理,统计最大值,获取某个属性集合等12种最常用方法
import com.alibaba.fastjson.JSON;
import org.assertj.core.util.Lists;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class StreamDemo {
public static void main(String[] args) {
User user1=new User("1","zhangsan",1);
User user2=new User("2","zhangsan",2);
User user3=new User("3","lisi",2);
List<User> userList= Lists.newArrayList();
userList.add(user1);
userList.add(user2);
userList.add(user3);
Map<String,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
System.out.println("1->"+userMap1);
Map<String,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
System.out.println("2->"+userMap2);
Map<String,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
System.out.println("3->"+userMap3);
Map<String,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getName, Function.identity(),(value1,value2)->value2));
System.out.println("4->"+userMap4);
Map<String, List<User>> userMap5 = userList.stream().collect(Collectors.groupingBy(User::getName));
System.out.println("5->"+userMap5);
Integer totalAge = userList.stream().map(User::getAge).reduce(0, Integer::sum);
System.out.println("6总年龄->"+totalAge);
Integer totalAgeFilter = userList.stream().filter(t -> t.getName().equals("zhangsan")).map(User::getAge).reduce(0, Integer::sum);
System.out.println("7总年龄filter->"+totalAgeFilter);
Integer maxAge = userList.stream().map(User::getAge).max((x, y) -> x - y).get();
System.out.println("8最大年龄->"+maxAge);
userList.stream().forEach(user -> System.out.println("9->"+user));
List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());
System.out.println("10名称集合->"+ JSON.toJSONString(nameList));
Map<String, Integer> map = userList.stream()
.collect(Collectors.toMap(p -> p.getName() + p.getAge() + p.getId(), User::getAge));
System.out.println("11->"+ JSON.toJSONString(map));
Map<String, List<User>> nameAgeMap = userList.stream()
.collect(Collectors.groupingBy(l -> l.getName() +"-" + l.getAge()));
System.out.println("12->"+ JSON.toJSONString(nameAgeMap));
}
}