Combine two lists with duplicate elements removed
Combine Stream.concat () and distinct ()
- When I came across a scene where I wanted to combine two lists while eliminating duplicate elements and was looking for something that could be cleaned up using the Stream API [Stream.concat ()](https://docs.oracle.com/en/java Because there was a convenient thing called /javase/13/docs/api/java.base/java/util/stream/Stream.html#concat (java.util.stream.Stream, java.util.stream.Stream)) , I did it well by combining this with
distinct ()
.
List<Integer> list1 = List.of(1, 2, 3, 4, 5);
List<Integer> list2 = List.of(0, 4, 5, 6, 7);
- Combine the above lists
list1
and list2
with duplicate elements removed
List<Integer> result = Stream.concat(list1.stream(), list2.stream())
.distinct()
.sorted(Comparator.naturalOrder()) //Sort in ascending order
.collect(Collectors.toList());
result.forEach(System.out::println); // -> 0,1,2,3,4,5,6,7