简体   繁体   English

Java8组列出要映射的列表

[英]Java8 group a list of lists to map

I have a Model and a Property class with the following signatures: 我有一个Model和一个带有以下签名的Property类:

public class Property {

    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

public class Model {

    private List<Property> properties = new ArrayList<>();

    public List<Property> getProperties() {
        return properties;
    }
}

I want a Map<String, Set<Model>> from a List<Model> where the key would be the name from the Property class. 我想从List<Model>Map<String, Set<Model>> ,其中键是Property类中的名称。 How can I can I use java8 streams to group that list by its Propery es' name? 我怎样才能使用java8流按其Propery es'名称对该列表进行Propery All Property es are unique by name. 所有Property都是名称唯一的。

It is possible to solve in a single stream or should I split it somehow or go for the classical solution? 可以在单个流中解决,还是应该以某种方式拆分它或者寻找经典的解决方案?

yourModels.stream()
          .flatMap(model -> model.getProperties().stream()
                  .map(property -> new AbstractMap.SimpleEntry<>(model, property.getName())))
          .collect(Collectors.groupingBy(
                Entry::getValue, 
                Collectors.mapping(
                    Entry::getKey, 
                    Collectors.toSet())));

Why not use forEach ? 为什么不使用forEach

Here is concise solution using forEach 这是使用forEach简洁解决方案

Map<String, Set<Model>> resultMap = new HashMap<>();
listOfModels.forEach(currentModel ->
        currentModel.getProperties().forEach(prop -> {
            Set<Model> setOfModels = resultMap.getOrDefault(prop.getName(), new HashSet<>());
            setOfModels.add(currentModel);
            resultMap.put(prop.getName(), setOfModels);
        })
); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM