Java Unique List

From EggeWiki

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();
list.add("A");
list.add("B");
list.add("A");
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(c);
    }

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.

<adsense> google_ad_client = 'pub-0027270078582348'; google_ad_width = 728; google_ad_height = 90; google_ad_slot = '9003651073'; google_ad_format = '728x90_as'; google_ad_type = 'text_image'; google_ad_channel = '3267063621'; google_color_border = 'FFFFFF'; google_color_bg = 'FFFFFF'; google_color_link = '3D81EE'; google_color_text = '000000'; google_color_url = '3D81EE'; </adsense>