【发布时间】:2022-01-16 08:46:51
【问题描述】:
我有以下物品:
class A {
int id;
String propA;
}
class B {
int id;
String propB;
}
class C {
int id;
String propA;
String propB;
}
给定对象 A 和 B 的列表,我想计算对象 C 的列表,这将是通过 id 将对象 A 与 B 连接起来创建的对象;但是,如果 id 存在于对象 A 而不是 B 或 B 而不是 A 的列表中,我想将其包含在对象 C 的列表中,但缺少属性。换句话说,在以下列表中加入:
List<A> listA = new ArrayList<>();
listA.add(new A(1, "example1"));
listA.add(new A(2, "example2"));
List<B> listB = new ArrayList<>();
listB.add(new B(2, "another example2"));
listB.add(new B(3, "another example3"));
应该相当于创建如下列表:
List<C> listC = new ArrayList<>();
listC.add(new C(1, "example1", null));
listC.add(new C(2, "example2", "another example2"));
listC.add(new C(3, null, "another example3"));
我已经看到使用 Stream API 解决了类似的问题,但它始终是片面的外连接;无论哪种方式,我都试图使其适应我的需求。
我的尝试如下:
//creating maps of ids to list elements, so I can access it from the final stream easily
Map<Integer, A> listAbyId = listA.stream().collect(Collectors.toMap(A::getId, Function.identity()));
Map<Integer, B> listBbyId = listB.stream().collect(Collectors.toMap(B::getId, Function.identity()));
//creating set of all ids that are in both lists
Set<Integer> set = listA.stream().map(a -> a.getId()).collect(Collectors.toSet());
Set<Integer> set2 = listB.stream().map(b -> b.getId()).collect(Collectors.toSet());
HashSet<Integer> setc = new HashSet<>();
setc.addAll(set);
setc.addAll(set2);
//final stream that creates list of C objects.
List<C> listC = setc.stream().map(c -> new C(c,
listAbyId.get(c) == null ? null : listAbyId.get(c).getPropA(),
listBbyId.get(c) == null ? null : listBbyId.get(c).getPropB()))
.collect(Collectors.toList());
它按预期工作,但似乎有点矫枉过正。有没有更简单的方法?
【问题讨论】:
标签: java java-stream