How to find duplicate elements in a Stream in Java Last Updated : 10 Jan, 2023 Comments Improve Suggest changes Like Article Like Report Given a stream containing some elements, the task is to find the duplicate elements in this stream in Java. Examples: Input: Stream = {5, 13, 4, 21, 13, 27, 2, 59, 59, 34} Output: [59, 13] Explanation: The only duplicate elements in the given stream are 59 and 13. Input: Stream = {5, 13, 4, 21, 27, 2, 59, 34} Output: [] Explanation: There are no duplicate elements in the given stream, hence the output is empty. There are many methods to find duplicate elements in a Stream: Using Set: Since Set has the property that it cannot contain any duplicate element. So if we add the elements in a Set, it automatically discards the duplicate elements while addition itself. Approach: Get the stream of elements in which the duplicates are to be found. Traverse each element of the stream For each element in the stream, if it is not present in the set, add it. This can be done using Set.add() method. Set.add() If the element is present in the Set already, then this Set.add() returns false. Hence we can print such elements or collect them for further process. We will print these elements in this case. Below is the implementation of the above approach: Example: Java // Java program to find the duplicate // elements in a Stream using Set import java.util.*; import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Set to store the duplicate elements Set<T> items = new HashSet<>(); // Return the set of duplicate elements return stream // Set.add() returns false // if the element was // already present in the set. // Hence filter such elements .filter(n -> !items.add(n)) // Collect duplicate elements // in the set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); } } Output: [59, 13] Using Collectors.groupingBy(): The groupingBy() method of Collectors class in Java groups the objects by some property. So we will pass the property of redundancy and collect the result in a Set. Approach: Get the stream of elements in which the duplicates are to be found. Traverse each element of the stream For each element in the stream, group them along with their frequency in a map, using Collectors.groupingBy() method. stream.collect( Collectors.groupingBy(Function.identity(), Collectors.counting())); Then for each element in the collected map, if the frequency of any element is more than one, then this element is a duplicate element. Hence we can print such elements or collect them for further process. We will print these elements in this case. Below is the implementation of the above approach: Example: Java // Java program to find the duplicate // elements in a Stream using Collectors.groupingBy() import java.util.*; import java.util.stream.*; import java.util.function.Function; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(Stream<T> stream) { // Return the set of duplicate elements return stream // Group the elements along // with their frequency in a map .collect( Collectors.groupingBy( Function.identity(), Collectors.counting())) // Convert this map into a stream .entrySet() .stream() // Check if frequency > 1 // for duplicate elements .filter(m -> m.getValue() > 1) // Find such elements .map(Map.Entry::getKey) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream Stream<Integer> stream = Stream.of(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(stream)); } } Output: [59, 13] Using Collections.frequency(): The frequency() method of Collections class in Java, counts the frequency of the specified element in the given list. So we will then find out the elements that have frequency more than 1, which are the duplicate elements. Approach: Get the stream of elements in which the duplicates are to be found. Traverse each element of the stream For each element in the stream, count the frequency of each element, using Collections.frequency() method. Collections.frequency(list, i) Then for each element in the collection list, if the frequency of any element is more than one, then this element is a duplicate element. Hence we can print such elements or collect them for further process. We will print these elements in this case. Below is the implementation of the above approach: Example: Java // Java program to find the duplicate // elements in a Stream // using Collections.frequency() import java.util.*; import java.util.stream.*; public class GfG { // Function to find the // duplicates in a Stream public static <T> Set<T> findDuplicateInStream(List<T> list) { // Return the set of duplicate elements return // Get the stream from the list list.stream() // Count the frequency of each element // and filter the elements // with frequency > 1 .filter(i -> Collections.frequency(list, i) > 1) // And Collect them in a Set .collect(Collectors.toSet()); } // Driver code public static void main(String[] args) { // Initial stream List<Integer> list = Arrays.asList(5, 13, 4, 21, 13, 27, 2, 59, 59, 34); // Print the found duplicate elements System.out.println( findDuplicateInStream(list)); } } Output: [59, 13] Comment More infoAdvertise with us Next Article How to find duplicate elements in a Stream in Java S SHUBHAMSINGH10 Follow Improve Article Tags : Java Java Programs java-stream Java-Collectors Java-Stream-programs Java-Collections-Class +2 More Practice Tags : Java Similar Reads How to Remove Duplicate Elements From Java LinkedList? Linked List is a part of the Collection in java.util package. LinkedList class is an implementation of the LinkedList data structure it is a linear data structure. In LinkedList due to the dynamical allocation of memory, insertions and deletions are easy processes. For removing duplicates from Examp 4 min read How to Remove Duplicate Elements from the Vector in Java? Using LinkedHashSet and TreeSet, duplicate elements are removed. Because the LinkedHashSet and TreeSet do not accept duplicate elements. Example: Input : vector = [1, 2, 3, 4, 2, 4] Output: vector = [1, 2, 3, 4] Input : vector = [a, b, a, c, d, a] Output: vector = [a, b, c, d]Approach 1: Using Linke 3 min read Find the first element of a Stream in Java Given a stream containing some elements, the task is to get the first element of the Stream in Java. Example: Input: Stream = {"Geek_First", "Geek_2", "Geek_3", "Geek_4", "Geek_Last"} Output: Geek_First Input: Stream = {1, 2, 3, 4, 5, 6, 7} Output: 1 There are many methods to the find first elements 3 min read Java Program for Last duplicate element in a sorted array We have a sorted array with duplicate elements and we have to find the index of last duplicate element and print index of it and also print the duplicate element. If no such element found print a message. Examples: Input : arr[] = {1, 5, 5, 6, 6, 7} Output : Last index: 4 Last duplicate item: 6 Inpu 2 min read Find the last element of a Stream in Java Given a stream containing some elements, the task is to get the last element of the Stream in Java.Example:Input: Stream={âGeek_Firstâ, âGeek_2â, âGeek_3â, âGeek_4â, âGeek_Lastâ}Output: Geek_LastInput: Stream={1, 2, 3, 4, 5, 6, 7}Output: 7Methods to Find the Last Element of a Stream in JavaThere are 4 min read Java Program to Remove Duplicate Elements From the Array Given an array, the task is to remove the duplicate elements from an array. The simplest method to remove duplicates from an array is using a Set, which automatically eliminates duplicates. This method can be used even if the array is not sorted.Example:Java// Java Program to Remove Duplicate // Ele 6 min read How does TreeMap Handle Duplicate Keys in Java ? In Java, when it comes to handling duplicate keys in a TreeMap, the class does not allow duplicate keys. If we try to insert a key-value pair with a key that already exists in the TreeMap, the new value will override the existing one associated with that key. Declaration of a TreeMap:TreeMap<KeyT 2 min read How to Remove Duplicates from a String in Java Using Hashing? Working with strings is a typical activity in Java programming, and sometimes we need to remove duplicate characters from a string. Using hashing is one effective way to do this. By assigning a unique hash code to each element, hashing enables us to keep track of unique items. This article will exam 2 min read How to Configure Java Priority Queue to Handle Duplicate Elements? In Java, PriorityQueue is the data structure that stores the elements based on their priorities and provides operations to efficiently retrieve and manipulate these elements based on their priorities. PriorityQueue handles the duplicate elements using a comparator. Comparator is a pre-defined interf 3 min read Java Program to Find Duplicate Words in a Regular Expression Given an Expression which is represented by String. The task is to find duplicate elements in a Regular Expression in Java. Use a map or set data structures for identifying the uniqueness of words in a sentence. Examples: Input : str = " Hi, I am Hritik and I am a programmer. " Output: I am Explanat 3 min read Like