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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -