Removing doubles from a list





-2
Date Submitted Sat. May. 10th, 2008 11:10 AM
Revision 1 of 1
Beginner Kelmi
Tags doubles | List | REMOVE | Set
Comments 3 comments
The method 'removeDoubles' uses a HashSet to remove double elements from a list without creating another list. The first occurrences of the multiple elements are kept, others will be removed. The order of the list will be preserved. The parameter list's iterator must support remove. Example of use is given in the main-method.

import java.util.*;

class RemoveDoubles {
       
        public static void main(String[] args) {
                List<String> animals = new ArrayList<String>();
                animals.add("Horse");
                animals.add("Crocodile");
                animals.add("Cat");
                animals.add("Hamster");
                animals.add("Cat");
                animals.add("Cat");
                animals.add("Crocodile");
                animals.add("Mouse");
                animals.add("Elk");
                System.out.println(animals);
                removeDoubles(animals);
                System.out.println(animals);
        }
       
        public static <E, T extends List<E>> T removeDoubles(T list) {
                Iterator<E> it = list.iterator();
                Set<E> s = new HashSet<E>();
                while (it.hasNext()) {
                        E elem = it.next();
                        if (!s.add(elem)) {
                                it.remove();
                        }
                }
                return list;
        }
}
 

Anssi N

Comments

Comments Why not
Fri. Jun. 6th, 2008 8:36 AM    Beginner bugmenot
  Comments LinkedHashSet
Fri. Jun. 6th, 2008 2:28 PM    Newbie mbaird
    Comments This site sux
Fri. Jun. 6th, 2008 4:06 PM    Newbie mbaird

Voting

Votes Up


Votes Down


Beginner bugmenot
Newbie mbaird