私のコードはコンパイルされていません。ここでは、コードは次のようになります。Java 8 Stream APIコレクタ - addAllは引数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,
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 classification;'と 'Collection features;'これは私があなたが応答した他のスレッドのCarの単純化された例で説明しようとした問題です。 –
qwerty1423