DeduplicateList.java

Download DeduplicateList.java

 1: // Demo of using a LinkedHashSet to deduplicate a List while preserving
 2: // the list order.  (Note sure if this is efficient, however it is clever.)
 3: //
 4: // Written 11/2015 by Wayne Pollock, Tampa Florida USA
 5: 
 6: import java.util.*;
 7: 
 8: class DeduplicateList
 9: {
10:    public static void main ( String [] args )
11:    {
12:       List<String> names = new ArrayList<>();
13:       names.add( new String( "Wayne" ) );
14:       names.add( new String( "Jane" ) );
15:       names.add( new String( "Anna" ) );
16:       names.add( new String( "Hiro" ) );
17:       names.add( new String( "Kim" ) );
18:       names.add( new String( "Wayne" ) );
19:       names.add( new String( "Anna" ) );
20:       names.add( new String( "Sam" ) );
21:       names.add( new String( "Wayne" ) );
22: 
23:       // De-duplicate the list
24:       System.out.println( "Before deduplication: " +
25:          Arrays.deepToString( names.toArray() ) );
26: 
27:       Set<String> dedupNames = new LinkedHashSet<>( names );
28:       names.clear();
29:       names.addAll( dedupNames );
30: 
31:       System.out.println( "After deduplication:  " +
32:          Arrays.deepToString( names.toArray() ) );
33:    }
34: }