Assume two lists:
List<Integer> list1 = Arrays.asList(1, 2, 3, 4, 5); List<Integer> list2 = Arrays.asList(3, 4, 5, 6, 7);
Using Stream.concat() + distinct()
List<Integer> union = Stream.concat(list1.stream(), list2.stream())
.distinct() // remove duplicates
.collect(Collectors.toList());
System.out.println(union);
Output:
[1, 2, 3, 4, 5, 6, 7]
Summary:
Stream.concat()merges the two streams..distinct()ensures only unique elements remain..collect(Collectors.toList())gathers the result into a new list.
