Java Unique List

From EggeWiki
Jump to: navigation, search

The Java collections bundled with the JDK do not provide a built in method to get the unique items from a list. Here's an easy an efficient way to get the unique items. Simply put your list into a set and then create a list again.

ArrayList list = new ArrayList();
Set set = new HashSet(list);
ArrayList b = new ArrayList(set);
assertEquals(2, b.size());

Why does this work? The HashSet constructor takes in a collection, and after creating setting up a map, adds all of the elements.

    public HashSet(Collection<? extends E> c) {
	map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));

addAll in turn attempts to add each item to the map. If the item already exists, it will be ignored. This requires the objects you are adding to have proper equals and hashCode implementations.

Similarly, the ArrayList constructor takes in a collection, and adds the items it it's internal array. The downside of this method is that the order of the items in the unique list will not be the same as those in the original. If maintaining order is important, simply use a LinkedHashSet instead of a HashSet, or if you want the items sorted, use a TreeSet instead of the HashSet.

Personal tools