1.使用Collectors.groupingBy(方法引用返回分组属性作为k)
2.使用Collectors.groupingBy(方法引用返回分组属性作为k,Collectors的静态类返回值)
3.使用reduce归并数据,reduce(存储新数据对象类型,新类型初始化,归并到同一个对象中)
List<Person> users = Arrays.asList(
new Person(18, "张三", "123", 1),
new Person(19, "李四", "124", 0),
new Person(20, "王五", "125", 1),
new Person(21, "赵六", "126", 0),
new Person(22, "田七", "127", 1),
new Person(24, "孙八", "128", 0),
new Person(27, "周九", "129", 1));
//根据性别分组
Map<Integer, List<Person>> group1 = users.stream().collect(Collectors.groupingBy(Person::getSex));
// group1.values().forEach(System.out::println);
// group1.entrySet().forEach(System.out::println);
//根据年龄段分组
Map<String, List<Person>> group2 = users.stream().collect(Collectors.groupingBy(u -> {
int age = u.getAge();
if (age >= 18 && age <= 20) {
return "18-20";
} else if (age >= 21 && age <= 23) {
return "21-23";
} else if (age >= 24 && age <= 26) {
return "24-26";
}else {
return "else";
}
}));
// group2.entrySet().forEach(System.out::println);
//统计性别人数
Map<Integer, Long> group3 = users.stream().collect(Collectors.groupingBy(Person::getSex,Collectors.counting()));
group3.entrySet().forEach(System.out::println);
//使用reduce来实现统计性别人数
Map<Integer, Long> group4 = users.stream().reduce(new HashMap<Integer,Long>(),(m,p)->{
m.put(p.getSex(),m.getOrDefault(p.getSex(),0L)+1);
return m;
},(m1,m2)->{
m1.putAll(m2);
return m1;
});
// group4.entrySet().forEach(System.out::println);
标签:java,stream,Collectors,Person,groupingBy,分组,new,users
From: https://www.cnblogs.com/blanset/p/16929137.html