//1、list转map,指定key-value,key,value是对象中的某个属性值.
Map<String,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
System.out.println("1->"+userMap1);
//2、list转map 指定key-value,key为属性值,value是对象本身
Map<String,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
System.out.println("2->"+userMap2);
//3、list转map 指定key-value,value是对象本身,Function.identity()是简洁写法,返回对象本身
Map<String,User> userMap3 = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));
System.out.println("3->"+userMap3);
//4、指定key-value,value是对象本身,Function.identity()是简洁写法,返回对象本身,遇到key 冲突的解决办法,选择第二个key的值value2覆盖第一个key的值value1。
Map<String,User> userMap4 = userList.stream().collect(Collectors.toMap(User::getName, Function.identity(),(value1,value2)->value2));
System.out.println("4->"+userMap4);
//5、指定key-value,按照name进行分组 value是对象集合
Map<String, List<User>> userMap5 = userList.stream().collect(Collectors.groupingBy(User::getName));
System.out.println("5->"+userMap5);
//6.统计所有age
Integer totalAge = userList.stream().map(User::getAge).reduce(0, Integer::sum);
System.out.println("6总年龄->"+totalAge);
//7.只对名称为zhangsan的age 进行统计汇总
Integer totalAgeFilter = userList.stream().filter(t -> t.getName().equals("zhangsan")).map(User::getAge).reduce(0, Integer::sum);
System.out.println("7总年龄filter->"+totalAgeFilter);
//8.获取最大age
Integer maxAge = userList.stream().map(User::getAge).max((x, y) -> x - y).get();
System.out.println("8最大年龄->"+maxAge);
//9.循环打印
userList.stream().forEach(user -> System.out.println("9->"+user));
//10.获取名称集合
List<String> nameList = userList.stream().map(User::getName).collect(Collectors.toList());
System.out.println("10名称集合->"+ JSON.toJSONString(nameList));
jdk8 Stream流中将集合转成map,重复key处理,统计最大值,获取某个属性集合等10种最常用方法
最新推荐文章于 2024-08-22 11:54:43 发布