Saturday, 7 November 2009

Using Collections to Sort

This is a simple example to remove Duplicates from a Collection.

The Strategy followed involves :

1) Copy the elements to a Set.
2) This causes all the duplicates to be eliminated.
3) Clear the List
4) Copy the contents of the Set to the List

I have also added a simple sort .

Hope this post is useful
___________________________________________________________________________________
public class Main {

public static void removeDuplicates(List objects){

Set unique = new HashSet();
for(Iterator o = objects.iterator();o.hasNext();)
unique.add(o.next());

objects.clear();
for(Iteratort = unique.iterator();t.hasNext();)
objects.add(t.next());
Collections.sort(objects,Collections.reverseOrder());
for(Object m:objects)
System.out.println(m);

}
public static void main(String[] args) {
List objects = new LinkedList();
objects.add("Bye");
objects.add("Hai");
objects.add("Hai");
objects.add("anand");
removeDuplicates(objects);
}

}

_________________________________________________________________________________

No comments:

Post a Comment