1、示例Person类
public class Person {
private String name;
private int age;
private List<String> languagesSpoken;
}
2、创建分分组的List
Person p1 = new Person("Bob", 21, Arrays.asList("English", "French", "German")); Person p2 = new Person("Alice", 33, Arrays.asList("English", "Chinese", "Spanish")); Person p3 = new Person("Joe", 43, Arrays.asList("English", "Dutch", "Spanish", "German")); //存放到list中 List<Person> people = Arrays.asList(p1,p2,p3);
3、通过Collectors.groupingBy对会说的语言进行分组
Map<String, List<Person>> langPersons =
people.stream()
.flatMap(p -> p.getLanguagesSpoken()
.stream()
.map(l -> new SimpleEntry<>(l,p)))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue,
Collectors.toList())));
方法说明:
1)flatMap
(类似C# AddRange),将多个Stream连接成一个Stream,不是用新值取代Stream的值,与Map有所区别,会重新生成一个Stream对象取而代之。
2)collect
就是一个归约操作,就像reduce一样可以接受各种做法作为参数,将流中的元素累积成一个汇总结果。具体的做法是通过定义新的Collector接口来定义的