Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java8 group a list of lists to map

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?

like image 852
Sunflame Avatar asked Mar 16 '18 09:03

Sunflame


2 Answers

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())));
like image 190
Eugene Avatar answered Oct 27 '22 22:10

Eugene


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);
        })
); 
like image 4
David Marques Avatar answered Oct 28 '22 00:10

David Marques