Java Streams - Get a “symmetric difference list” from two other lists

前端 未结 6 2074
囚心锁ツ
囚心锁ツ 2021-01-05 01:17

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

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-05 02:04

    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.

提交回复
热议问题