Stream: Remove duplicates from List
In this Java code snippet, we’re dealing with a list of integers: 1, 2, 2, 3, 4, 4, and 5. Using streams, we’re filtering out duplicate values, resulting in a list of distinct numbers.
The `distinct` operation ensures that each value appears only once in the resulting list.
The code snippet efficiently creates the `distinctNumbers` list, which contains the unique integers from the original list: 1, 2, 3, 4, and 5. Streams simplify this process, making the code concise and effective.
</pre> List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5); List<Integer> distinctNumbers = numbers.stream() .distinct() .collect(Collectors.toList());