Самый чистый способ, который я могу придумать, - использовать HashMap
вместо List
, затем использовать Id
в качестве ключа и фактический объект в качестве значения, что упрощает поиск. Также создайте полный конструктор для C
:
A a1 = new A(1234, "foo", "bar");
A a2 = new A(12347, "baz", "quux");
B b1 = new B(2345, "example street", "city");
B b2 = new B(1234, "test street", "town");
HashMap<Long, A> aHashMap = new HashMap<Long, A>();
HashMap<Long, B> bHashMap = new HashMap<Long, B>();
aHashMap.put(a1.getId(), a1);
aHashMap.put(a2.getId(), a2);
bHashMap.put(b1.getId(), b1);
bHashMap.put(b2.getId(), b2);
List<C> cList = aHashMap.entrySet().stream()
.filter(entry->bHashMap.containsKey(entry.getKey()))
.map(entry -> {
B matchingB = bHashMap.get(entry.getKey());
return new C(entry.getKey(),
entry.getValue().getName(),
entry.getValue().getAge(),
matchingB.getAddress(),
matchingB.getCity());
})
.collect(Collectors.toList());
System.out.println(cList.toString());
Returns (я изменил toString()
):
[C{id=1234, name='foo', age='bar', address='test street', city='town'}]