Java8分组要映射的列表列表
我有一个 Model
和一个具有以下签名的 Property
类:
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;
}
}
我想要 List<Model>
中的 Map<String, Set<Model>>
,其中键是 Property<中的名称/代码>类.如何使用 java8 流按其
Propery
es 名称对该列表进行分组?所有 Property
的名称都是唯一的.
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())));
相关文章