我有一个像这样的对象:
public class Questionnaire(){ 私有字符串名称; 私人清单<类型>类型; // getter和setter}然后我有一份问卷清单:
名单< …
有解决方法 flatMap 之前 groupingBy :
flatMap
groupingBy
Map<Type, List<Questionnaire>> collect = questionnaires.stream() .flatMap(q -> q.getTypes().stream() .map(t -> new AbstractMap.SimpleEntry<>(t, q))) .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList())));
我创建了一个容器类:
class TypeQuestionnaire { private Questionnaire questionnaire; private Type type; }
这有助于我进行以下分组:
questionnaires.stream() .flatMap(q -> q.getTypes() .stream() .map(t -> new TypeQuestionnaire(q, t))) .collect(groupingBy(TypeQuestionnaire::getType), mapping(toList())));