Suppose I have this Java 8 code:
public class Foo {
private long id;
public getId() {
return id;
}
//--snip--
}
//Somewhere else...
List<Foo> listA = getListA();
List<Foo> listB = getListB();
List<Foo> uniqueFoos = ???;
In List<Foo> uniqueFoos
I want to add all elements of listA
and listB
so all Foo
s have unique IDs. I.e. if there is already a Foo
in uniqueFoos
that has a particular ID don't add another Foo
with the same ID but skip it instead.
Of course there is plain old iteration, but I think there should be something more elegant (probably involving streams, but not mandatory), but I can't quite figure it out...
I can think of good solutions involving an override of the equals()
method to basically return id == other.id;
and using a Set
or distinct()
. Unfortunately I can't override equals()
because object equality must not change.
What is a clear and efficient way to achieve this?