list聚合map
Map<Integer, String> stringMap = persons.stream().collect(
Collectors.toMap(
Person::getId,
Person::getName,
(value1, value2) -> value1));
Map<Integer, String> stringMap2 = persons.stream().collect(
Collectors.groupingBy(
Person::getId,
Collectors.collectingAndThen(
Collectors.toList(),
ele -> ele.get(0).getName())));
生成
List<Integer> generate = Stream.generate(() -> new
Random().nextInt(10)).distinct().limit(10).collect(Collectors.toList());
List<Integer> collect = Stream.iterate(0, a -> a + 1).limit(10).collect(Collectors.toList());
归约
Map<String, Long> countMap = albumList.stream().collect(Collectors.groupingBy(Album::getMusician,
Collectors.counting()));
System.out.println(countMap);
Map<String, List<String>> nameMap = albumList.stream().collect(Collectors.groupingBy(Album::getMusician,
Collectors.mapping(Album::getName, Collectors.toList())));
System.out.println(nameMap);
Map<String, String> nameStringMap = albumList.stream().collect(Collectors.groupingBy(Album::getMusician,
Collectors.mapping(Album::getName, Collectors.joining(", ", "{", "}"))));
System.out.println(nameStringMap);
nameStringMap = albumList.stream().collect(
Collectors.toMap(Album::getMusician, Album::getName,
(name1, name2) -> name1 + ", " + name2));
System.out.println(nameStringMap);
nameStringMap = albumList.stream().collect(
Collectors.groupingBy(Album::getMusician,
Collectors.reducing("", Album::getName, (value1, value2) -> value1 + ", " + value2)));
System.out.println(nameStringMap);
List<Integer> generate = Stream.generate(() -> new
Random().nextInt(10)).distinct().limit(10).collect(Collectors.toList());
多重分组
Map<String, Map<String, List<Person>>> multiGrouping = persons.stream().collect(Collectors.groupingBy(Person::getGender, Collectors.groupingBy(Person::getName)));
自定义分组
Map<String, List<Person>> selfDefinedGrouping = persons.stream().collect(Collectors.groupingBy(ele -> {
if (ele.getAge() <= 38) {
return "young";
} else if (ele.getAge() <= 58) {
return "medium";
} else {
return "old";
}
}));
分区
Map<Boolean, Map<String, List<Person>>> partitions = persons.stream().collect(
Collectors.partitioningBy(
ele -> ele.getAge() >= 40,
Collectors.groupingBy(Person::getGender)));
评论前必须登录!
注册