我有两组,每组两个不同的类。这些类的对象几乎没有共同的属性。我想将这两个集合的对象合并在一起,它们具有相同的通用属性值并创建第三个对象。
例如:
class class1 {
String A;
String B;
String C;
}
class class2 {
String A;
String B;
String D;
}
我有两个带有set1对象的set1和带有class2对象的set2。
我想创建一组class3,它是class1和class2的组合,其中class1和class2的对象的A和B值相等。
class class3 {
String A;
String B;
String C;
String D;
}
最坏的情况下,我可以迭代两个集合,但是我试图找出是否有有效的解决方案来实现这一目标。
您需要迭代两个集合以找到公用值,以下是我使用流的方法
List<class3> list = set1.stream()
.map(s1->new AbstractMap.SimpleEntry<class1, class2>(s1,
set2.stream()
.filter(s2->s1.getA().equals(s2.getA()) && s1.getB().equals(s2.getB()))
.findFirst()
.orElse(null)))
.filter(entry->Objects.nonNull(entry.getValue()))
.map(ety->new class3(ety.getKey().getA(), ety.getKey().getB(), ety.getKey().getC(), ety.getValue().getD()))
.collect(Collectors.toList());