如何分区Java List
得到以下两种类型的列表:
我目前的工作方法是使用forEach
如下:
Map<String, Set<Attribute>> applicableAttributeMap = new HashMap<>();
Set<Attribute> unionMandatoryAttributes = new HashSet<>();
Set<Attribute> intersectedAttributes = new HashSet<>();
givenNames.forEach(givenName -> {
List<Attribute> applicableAttributes = getAllApplicableAttributes(givenName); //function to retrieve List<Attribute> by passing givenName
if (applicableAttributes != null && !applicableAttributes.isEmpty()) {
unionMandatoryAttributes.addAll(
applicableAttributes
.stream()
.filter(Attribute::getIsRequired)
.collect(Collectors.toSet())
);
if (intersectedAttributes.isEmpty()) {
intersectedAttributes.addAll(applicableAttributes);
}
intersectedAttributes.retainAll(applicableAttributes);
}
});
applicableAttributeMap.put(UnionMandatory, unionMandatoryAttributes);
applicableAttributeMap.put(IntersectedAll, intersectedAttributes);
我正在尝试使用 简化上面的代码块partitioningBy
,但我无法获得所需的输出。我无法收集另一个包含所有元素和Map
's key
as 的列表String
。
这是我的partitioningBy
方法:
Map<Boolean, Set<Attribute>> applicableMap = givenNames
.stream()
.flatMap(s -> getAllApplicableAttributes(s).stream())
.filter(Objects::nonNull)
.collect(Collectors.partitioningBy(
Attribute::getIsRequired,
Collectors.mapping(Function.identity(),Collectors.toSet())
));
我如何创建Map<String , Set<Attributes>>
满足工作方法或任何其他简化解决方案中给出的条件?
(注意:所以我的目标是实现工作方法发生的确切情况,我可能在解释问题时遗漏了一些东西。但最重要的是通过使用类似的方法或任何比什么更好的方法来获得与工作方法相同的结果partitioningBy
我弄完了。)
迭代两次givenNames
看起来是最好的方法:
Map<String, Set<Attribute>> applicableAttributeMap = new HashMap<>();
List<String> givenNames = ImmutableList.copyOf(....);
Set<Attribute> unionMandatoryAttributes =
givenNames.stream()
.map(this::getAllApplicableAttributes)
.flatMap(Collection::stream)
.filter(Attribute::getIsRequired)
.collect(Collectors.toSet());
Set<Attribute> intersectedAttributes = ImmutableSet.of();
if (givenNames.size() > 0) {
intersectedAttributes = this.getAllApplicableAttributes(givesNames.get(0));
for (int i = 1; i < givenNames.size(); i++) {
intersectedAttributes = Sets.intersection(intersectedAttributes, getAllApplicableAttributes(givesNames.get(i)));
}
}
applicableAttributeMap.put("UnionMandatory", unionMandatoryAttributes);
applicableAttributeMap.put("IntersectedAll", intersectedAttributes);
}
请注意,此代码依赖于番石榴的ImmutableList
,ImmutableSet
和Sets.intersection
。
还要注意getAllApplicableAttributes
此代码中调用的次数翻了一番。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句