Java8 group a list of lists to map

无人久伴 提交于 2020-05-07 19:15:28

问题


I have a Model and a Property class with the following signatures:

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. How can I can I use java8 streams to group that list by its Properyes' name? All Propertyes are unique by name.

It is possible to solve in a single stream or should I split it somehow or go for the classical solution?


回答1:


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())));



回答2:


Why not use forEach ?

Here is concise solution using 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);
        })
); 


来源:https://stackoverflow.com/questions/49317168/java8-group-a-list-of-lists-to-map

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!