Im trying to use Java 8 streams to combine lists. How can I get a \"symmetric difference list\" (all object that only exist in one list) from two existing lists. I know how
the lambda solution with groupingBy
:
the map values with the true
-key are in both lists
the map values with the false
-key are disjoint
Map> map = Stream.concat(bigCarList.stream(),
smallCarList.stream()).collect(
groupingBy( b -> bigCarList.stream().anyMatch( s -> b.equals( s ) )
&& smallCarList.stream().anyMatch( s -> b.equals( s ) ) ) );
List disjoint = map.get( false ); // [Toyota Corolla, Ford Focus]
same principle but shorter w/o inline streams:
Map> map = Stream.concat(bigCarList.stream(),
smallCarList.stream()).collect(
groupingBy( b -> bigCarList.contains( b )
&& smallCarList.contains( b ) ) );
List disjoint = map.get( false ); // [Toyota Corolla, Ford Focus]
both are working with duplicates as well
means: duplicates in one list that are not contained in the other list
If the amount of data is not so huge that you are running into disk space issues, a simple groupingBy
‑ without filtering or additional queries to reduce the result set ‑ should be the clearest and fastest solution.