实体类定义:
@Data
public class User {
private String userName;
private int age;
public User() {
}
public User(String userName, int age) {
this.userName = userName;
this.age = age;
}
}
收集器使用案例:
public static void main(String[] args) {
List<User> list = new ArrayList<User>(
Arrays.asList(
new User("TangLingYun", 28),
new User("TangLingYun1", 21),
new User("TangLingYun2", 22),
new User("TangLingYun4", 22),
new User("TangLingYun3", 23)));
// 数据提取
TreeSet<Integer> treeSet = list.stream().map(User::getAge).collect(Collectors.toCollection(TreeSet::new));
System.err.println(treeSet);
// 聚合函数
IntSummaryStatistics intSummaryStatistics = list.stream().collect(Collectors.summarizingInt(User::getAge));
System.err.println(intSummaryStatistics);
// 分块 数据筛选
Map<Boolean, List<User>> map = list.stream().collect(Collectors.partitioningBy(u -> u.getAge() < 28));
System.err.println(map);
// 分组
Map<Integer, List<User>> collect = list.stream().collect(Collectors.groupingBy(User::getAge));
System.err.println(collect);
// 分组 个数
Map<Integer, Long> collect2 = list.stream().collect(Collectors.groupingBy(User::getAge,Collectors.counting()));
System.err.println(collect2);
}
输出结果:
[21, 22, 23, 28]
IntSummaryStatistics{count=5, sum=116, min=21, average=23.200000, max=28}
{false=[User@2d554825], true=[User@68837a77, User@6be46e8f, User@3567135c, User@327471b5]}
{21=[User@68837a77], 22=[User@6be46e8f, User@3567135c], 23=[User@327471b5], 28=[User@2d554825]}
{21=1, 22=2, 23=1, 28=1}
网友评论