Home > Java Tips and Tricks > How to retain/get only the duplicate elements in a list

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

February 5th, 2011

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.

Java Tips and Tricks

  1. No comments yet.
  1. No trackbacks yet.