Removing double entries from a List





9
Date Submitted Wed. Dec. 27th, 2006 9:40 AM
Revision 1 of 1
Scripter bertheymans
Tags Java | List | Set | uniqueness
Comments 2 comments
This is a very convenient way to remove all doubles from a List in Java. The only prerequisite is that the elements in the list have proper equals and hashCode methods.

It work by using the constructor of a Set that takes a Collection as an argument.

I poured the snippet in a little program so can run it straight away.

import java.util.*;

public class RemoveDoubles {
    public static void main(String[] args) {
        // illustrating that a set filters doubles
        ArrayList list = new ArrayList();
        list.add("a");
        list.add("a");
        list.add("c");

        System.out.println("list.size(): " + list.size());
        System.out.println("list: " + list);

        HashSet set = new HashSet(list);
        System.out.println("set.size(): " + set.size());
        System.out.println("set: " + set);


        list = new ArrayList(set);
        System.out.println("list: " + list);
    }
}

/*
list.size(): 3
list: [a, a, c]
set.size(): 2
set: [a, c]
list: [a, c]
*/

 

Bert Heymans

blog.heymans.org

Comments

Comments Order
Wed. Dec. 27th, 2006 3:40 PM    Scripter SCoon
  Comments that's true
Thu. Dec. 28th, 2006 7:06 AM    Scripter bertheymans

Voting