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
Saturday, 7 November 2009
Pearls in Java
Pearl 1: Foreach Loop in Java
In Java foreach is written as for(int i: in collection)
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. The for-each loop hides the iterator, so you cannot callremove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
In Java foreach is written as for(int i: in collection)
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. The for-each loop hides the iterator, so you cannot callremove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
Subscribe to:
Posts (Atom)