Java8 group a list of lists to map

Sunflame :

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?

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474483&siteId=1