Home > Collections, Java > How to retain/get only the duplicate elements in a list

How to retain/get only the duplicate elements in a list

Let’s say you have a list of duplicate (and non-duplicate) items, and you want a new collection with only the duplicate items in there. The easiest way is to extend the HashSet.

public class DuplicatesOnlySet<E> extends HashSet<E>
{
    private final Set<E> uniques = new HashSet<E>();

    public  DuplicatesOnlySet(Collection<? extends E> c) 
    {
        super.addAll(c);
    }

    @Override
    public boolean add(E e) 
    {                
        if(!this.uniques.add(e))
             return super.add(e);

    return false;
    }
}

Call it like

List<String> duplicates = new ArrayList<String>(new DuplicatesOnlySet<String>(original)) ;

where original is the Collection with the duplicate items.

Compliments to Markos for his implementation.

Advertisements
  1. Bhupendra
    1 April 2011 at 8:36 am

    Thanks..Great

  2. saj
    6 September 2012 at 1:44 pm

    Very Nice!

  3. vikram
    3 April 2013 at 10:38 pm

    It doesnt work Dude!!!!!!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: