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 Propery
es' name? All Property
es 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?
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
?
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);
})
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With