× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Find duplicate elements of a Collection

<pre><code class="language-java">import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.Set; public static &lt;T&gt; Collection&lt;T&gt; findDuplicates(final Collection&lt;T&gt; collection) { if (collection == null) { return Collections.emptySet(); } Set&lt;T&gt; duplicates = new HashSet&lt;&gt;(); Set&lt;T&gt; uniques = new HashSet&lt;&gt;(); for (T t : collection) { if (!uniques.add(t)) { duplicates.add(t); } } return duplicates; }</code></pre> <p>The code above finds and returns all duplicated elements of a given <em>generic collection</em>.</p> <p>The idea is to use the boolean return value of the Set.add method which returns false if the element you try to add already exists in the collection.</p> <p>This code works with Java types -- the only optional requirement is that they should implement the equals and hashCode methods properly.</p>

Get New Tutorials Delivered to Your Inbox

New tutorials will be sent to your Inbox once a week.

comments powered by Disqus