[JAVA] Combine two lists with duplicate elements removed

Combine Stream.concat () and distinct ()

List<Integer> list1 = List.of(1, 2, 3, 4, 5);
List<Integer> list2 = List.of(0, 4, 5, 6, 7);
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

Recommended Posts

Combine two lists with duplicate elements removed
Combine Java8 lists
[Ruby] Exclude duplicate elements with the uniq method.