基本上
Stream,您需要一个由
Pair(我
AbstractMap.SimpleEntry在这里选择)的组件构成,该组件的左边部分为爱好,右边为学生(可以相反,这没关系)。
以后只需将其基于
Hobby(根据您的情况为String)进行分组。
data.stream() .flatMap(student -> student.getHobbies().stream().map(hobby -> new SimpleEntry<>(hobby, student))) .collect(Collectors.groupingBy( Entry::getKey, Collectors.mapping(Entry::getValue, Collectors.toList())));
Entry::getKey作为获取键的方法引用,如果对您更有意义,也可以将其编写为lambda表达式:
Collectors.groupingBy(entry -> entry.getKey())



