Remove Duplicates in Java Streams
In Java, you can remove duplicates with the distinct() method of a stream and collect the results into a new collection using the collect() method.
For example, suppose there is a List that contains duplicate elements.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 2, 3, 4);
To remove duplicates and extract unique elements, you can follow the steps below:
- Convert the list to a stream.
Stream<Integer> numberStream = numbers.stream();
- Remove duplicates using the distinct() method.
Stream<Integer> distinctStream = numberStream.distinct();
- Use the collect() method to gather the results into a new collection.
List<Integer> distinctNumbers = distinctStream.collect(Collectors.toList());
In this way, distinctNumbers now contains the unique elements: [1, 2, 3, 4, 5].
To retrieve duplicate elements, you can use the filter() method to select the duplicate elements and then use the collect() method to gather the results into a new collection. For example, to retrieve the duplicate elements 2, 3, and 4, you can follow these steps:
- Convert the List to a stream.
Stream<Integer> numberStream = numbers.stream();
- Use the filter() method to select duplicate elements:
Stream<Integer> duplicateStream = numberStream.filter(i -> Collections.frequency(numbers, i) > 1);
- Use the collect() method to collect the results into a new collection.
List<Integer> duplicateNumbers = duplicateStream.distinct().collect(Collectors.toList());
In this way, the duplicateNumbers list contains duplicate elements: [2, 3, 4].