1.0、初始化数据
伪代码
User a1 = User.builder().age(2).name("A").build();
User a = User.builder().age(1).name("A").build();
User b = User.builder().age(2).name("B").build();
User c = User.builder().age(3).name("C").build();
User d = User.builder().age(4).name("D").build();
List<User> userList = Lists.newArrayList(a1,a,b, c, d);
User flatUser1 = User.builder().age(4).name("as,df,gh").build();
User flatUser2 = User.builder().age(4).name("gh,jk").build();
List<User> flatUserList = Lists.newArrayList(flatUser1,flatUser2);
1.1、toMap
key值相同时的策略
//k1和k2重复,返回k2
Map<String, User> collectK2 = userList.stream().collect(Collectors.toMap(User::getName, Function.identity(), (k1, k2) -> k2));
//按照自定义条件返回key,例如按照最大age返回key
Map<String, User> collectMax = userList.stream().collect(Collectors.toMap(User::getName, Function.identity(), BinaryOperator.maxBy(Comparator.comparing(User::getAge))));
1.2、flatMap
map 的输入和输出是 1:1
flatMap的输入和输出是 1:N
//map 的输入和输出是 1:1
//如果直接用map取值,则输出 [[Ljava.lang.String;@2a2d45ba, [Ljava.lang.String;@2a5ca609]
flatUserList.stream().map(var -> var.getName().split(",")).collect(Collectors.toList());
//使用flatMap 则输出 [as, df, gh, jk]
//flatMap的输入和输出是 1:N
flatUserList.stream().map(var->var.getName().split(",")).flatMap(Arrays::stream).distinct().collect(Collectors.toList());
1.3、groupingBy
分组策略-分组字段重复时取值逻辑
//默认value是list
userList.stream().collect(Collectors.groupingBy(User::getName));
//指定value返回类型
userList.stream().collect(Collectors.groupingBy(User::getName,Collectors.toSet()));
//分组策略-保留age最大的那一条
userList.stream().collect(Collectors.groupingBy(User::getName, Collectors.maxBy(Comparator.comparing(User::getAge))));
//分组策略-保留age最小的那一条
userList.stream().collect(Collectors.groupingBy(User::getName, Collectors.minBy(Comparator.comparing(User::getAge))));
1.4、collectingAndThen
对象集合去重
//name属性去重
userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getName))), ArrayList::new));
//name和age去重
userList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() ->new TreeSet<>(Comparator.comparing(user -> user.getName()+ "-" + user.getAge()))), ArrayList::new));
1.5、maxBy/minBy
取最大最小值
// 最大、最小age
userList.stream().collect(Collectors.maxBy(Comparator.comparing(User::getAge)));
userList.stream().collect(Collectors.minBy(Comparator.comparing(User::getAge)));
1.6、reduce
累加求和
// reduce、reducing、summingInt 效果一样
userList.stream().map(User::getAge).reduce(0, (x, y) -> x + y));
userList.stream().map(User::getAge).collect(Collectors.reducing(0,Integer::sum));
userList.stream().map(User::getAge).collect(Collectors.summingInt(Integer::intValue));
标签:Collectors,stream,userList,age,用法,collect,User,知道
From: https://www.cnblogs.com/geekdc/p/17262814.html