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

前端 未结 6 2078
囚心锁ツ
囚心锁ツ 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:13

    An alternative approach, albeit not as elegant as one line streams:

        HashMap y = new HashMap<>();
        bigCarSet ().forEach(i -> y.put(i, !y.containsKey(i)));
        bigCarList().forEach(i -> y.put(i, !y.containsKey(i)));
        y.entrySet().stream().filter(Map.Entry::getValue).map(Map.Entry::getKey)
         .collect(Collectors.toList());
    

    which can be simplified to at least:

        HashMap y = new HashMap<>();
        Stream.concat(list1.stream(), list2.stream()).forEach(i -> y.put(i, !y.containsKey(i)));
        y.entrySet().stream().filter(Map.Entry::getValue)
                     .map(Map.Entry::getKey).collect(Collectors.toList());
    

提交回复
热议问题