Java Stream distinct: Remove Duplicates

You can use the distinct operator to remove duplicate data from a stream. This operator will return a stream with no duplicates, determining if elements are repeated based on their equals method.

Here is an example code:

List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 3, 2, 1);

List<Integer> distinctNumbers = numbers.stream()
                                      .distinct()
                                      .collect(Collectors.toList());

System.out.println(distinctNumbers);  // 输出: [1, 2, 3, 4]

In the example above, we removed duplicate elements in the numbers stream by using the distinct operator and collected the result into a new list. The final output is the deduplicated list [1, 2, 3, 4].

bannerAds