java - How can I merge and then distinct collections with the Stream API? -
this question has answer here:
let's prefix objects equals implementation not how need filter distinct not work.
class myobject { string foo; myobject( string foo ) { this.foo = foo; } public string getfoo() { return foo; } } collection<myobject> lista = arrays.aslist("a", "b", "c").stream().map(myobject::new) .collect(collectors.tolist()); collection<myobject> listb = arrays.aslist("b", "d").stream().map(myobject::new) .collect(collectors.tolist()); // magic how can merge , deduplicate lists resulting list should of myobjects containing "a", "b", "c", "d"?
note: simplification of methods need deduplicate, complex dtos of entities loaded hibernate, example should adequately demonstrate objective.
if .equals() not work may want have go @ using guava's equivalence.
provided type t, need implement equivalence<t>; once have this, need create a:
set<equivalence.wrapper<t>> into you'll gather values. then, provided implementation of equivalence<t> static variable named eq, adding set simple as:
coll1.stream().map(eq::wrap).foreach(set::add); coll2.stream().map(eq::wrap).foreach(set::add); and obtain list<t> set, could:
final set<t> unwrapped = set.stream().map(equivalence.wrapper::get) .collect(collectors.toset()); but of course, since in comments can loop, well... why not keep using loop?
if works, don't fix it...
Comments
Post a Comment