写在前面
一、分组实现
1.1、简单分组
Map<String, Long> departmentNames = departmentDbs.stream()
.collect(Collectors.toMap(
Department::getDepartmentName,
Department::getDepartmentId)
);
1.2、集合分组
@Test
public void t12_2() {
List<Person> roster = Arrays.asList(
new Person("as", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zx", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zc", LocalDate.now(), Person.Sex.MALE,"Test@",12),
new Person("zv", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zb", LocalDate.now(), Person.Sex.MALE,"Test@",12),
new Person("zn", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zm", LocalDate.now(), Person.Sex.MALE,"Test@",12)
);
Map<Person.Sex, List<Person>> collect = roster.stream()
.collect(
Collectors.groupingBy(Person::getGender)
);
collect.forEach((k,v) -> System.out.println(k + " : " + v));
}
1.3、分组求和
@Test
public void t14() {
List<Person> roster = Arrays.asList(
new Person("as", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zx", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zc", LocalDate.now(), Person.Sex.MALE,"Test@",12),
new Person("zv", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zb", LocalDate.now(), Person.Sex.MALE,"Test@",12),
new Person("zn", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zm", LocalDate.now(), Person.Sex.MALE,"Test@",12)
);
Map<Person.Sex, Integer> totalAgeByGender =
roster.stream()
.collect(
Collectors.groupingBy(
Person::getGender,
Collectors.reducing(
0,
Person::getAge,
Integer::sum))
);
totalAgeByGender.forEach((k,v) -> System.out.println(k + " : " + v));
}
1.4、分组求平均
@Test
public void t15() {
List<Person> roster = Arrays.asList(
new Person("as", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zx", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zc", LocalDate.now(), Person.Sex.MALE,"Test@",12),
new Person("zv", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zb", LocalDate.now(), Person.Sex.MALE,"Test@",12),
new Person("zn", LocalDate.now(), Person.Sex.FEMALE,"Test@",12),
new Person("zm", LocalDate.now(), Person.Sex.MALE,"Test@",12)
);
Map<Person.Sex, Double> averageAgeByGender = roster.stream()
.collect(
Collectors.groupingBy(
Person::getGender,
Collectors.averagingInt(Person::getAge)));
averageAgeByGender.forEach((k,v) -> System.out.println(k + " : " + v));
}