我的代码不编译,我不太清楚为什么。下面是代码:Java 8流API收集器 - addAll不适用于参数对象,addAll未定义类型对象
ArrayList<ClassificationData> classifications = productData
.stream()
.filter(p -> CollectionUtils.isNotEmpty(p.getClassifications()))
.flatMap(p -> p.getClassifications().stream())
.collect(groupingBy(ClassificationData::getName,
mapping(ClassificationData::getFeatures,
Collector.of(LinkedHashSet<FeatureData>::new,
(a,b) -> b.addAll(a),
(a,b) -> {
b.addAll(a);
return b;
})
)))
.entrySet()
.stream()
.map(e -> {
ClassificationData c = new ClassificationData();
c.setName(e.getKey());
c.setFeatures(e.getValue());
return c;
})
.collect(Collectors.toCollection(ArrayList::new));
而且错误:
(a,b) -> b.addAll(a),
The method addAll(Collection<? extends FeatureData>) in the type Collection<FeatureData> is not applicable for the arguments (Object)
b.addAll(a);
The method addAll(Object) is undefined for the type Object
c.setFeatures(e.getValue());
The method setFeatures(Collection<FeatureData>) in the type ClassificationData is not applicable for the arguments (Object)
我也尝试设置与::几乎相同的结果添加和设置::中的addAll。
编辑:
我已经结束了这段代码。请告诉我是否有更干净的方式来做到这一点,还是可以吗?
ArrayList<ClassificationData> classifications = productData
.stream()
.filter(p -> CollectionUtils.isNotEmpty(p.getClassifications()))
.flatMap(p -> p.getClassifications().stream())
.collect(groupingBy(ClassificationData::getName,
mapping(ClassificationData::getFeatures,
toCollection(LinkedHashSet::new)
)))
.entrySet()
.stream()
.map(e -> {
ClassificationData c = new ClassificationData();
c.setCode(e.getKey());
c.setName(e.getKey());
c.setFeatures(e.getValue()
.stream()
.filter(CollectionUtils::isNotEmpty)
.flatMap(p -> p.stream())
.filter(distinctByKey(FeatureData::getName))
.collect(toCollection(ArrayList::new)));
return c;
})
.collect(toCollection(ArrayList::new));
我建议你添加一些类型信息给自己提示,因为类型混淆的原因可能在此代码中的任何地方。很可能你有一个原始类型的地方。 –
您的解决方案包含了可能需要昂贵的'Set'散列,并且可能需要更多的临时内存。您的原始代码可以正常使用'javac'和适当的'ClassificationData'和'FeatureData'声明。或者,您没有显示的ClassificationData和FeatureData的定义存在问题,或者您正在使用Eclipse,这在类型推断中有时会遇到问题。 – Holger
@Holger我正在使用Oracle Java 8. ClassificationData和FeatureData都是自动生成的DTO,因此我无法对它们做太多的工作。使用的字段是'Collection分类;'''''集合特征;'这是我尝试用其他线程中Car的简单示例来描述的问题,您已经回复了这个问题。 –
qwerty1423