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

前端 未结 6 2103
囚心锁ツ
囚心锁ツ 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 01:56

    Something like this may work:

    Stream.concat(bigCarList.stream(), smallCarList.stream())
          .collect(groupingBy(Function.identity(), counting()))
          .entrySet().stream()
          .filter(e -> e.getValue().equals(1L))
          .map(Map.Entry::getKey)
          .collect(toList());
    

    Here we first collect all the cars to the Map where value is the number of such cars encountered. After that, we filter this Map leaving only cars that are encountered exactly once, drop the counts and collect to the final List.

提交回复
热议问题