【DataStructure】Charming usage of Set in the java

【DataStructure】Charming usage of Set in the java

In an attempt to remove duplicate elements from list, I go to the lengths to take advantage of  methods in the java api. After investiagting the document of java api, the result is so satisfying that I speak hightly of wisdom of developer of java language.Next I will introduce charming usage about set in the java. 

[java] view plaincopy
  1. import java.util.ArrayList;  
  2. import java.util.Arrays;  
  3. import java.util.Collections;  
  4. import java.util.HashSet;  
  5. import java.util.List;  
  6. import java.util.Set;  
  7. import java.util.TreeSet;  
  8.   
  9. public class SetUtil  
  10. {  
  11.   
  12.     public static List<String> testStrList = Arrays.asList("Apple""Orange",  
  13.             "Pair""Grape""Banana""Apple""Orange");  
  14.   
  15.     /** 
  16.      * Gets sorted sets which contains no duplicate elements 
  17.      *  
  18.      * @time Jul 17, 2014 7:58:16 PM 
  19.      * @return void 
  20.      */  
  21.     public static void sort()  
  22.     {  
  23.         Set<String> sortSet = new TreeSet<String>(testStrList);  
  24.         System.out.println(sortSet);  
  25.       // output : [Apple, Banana, Grape, Orange, Pair]  
  26.     }  
  27.   
  28.     public static void removeDuplicate()  
  29.     {  
  30.         Set<String> uniqueSet = new HashSet<String>(testStrList);  
  31.         System.out.println(uniqueSet);  
  32.        <span style="font-family: Arial, Helvetica, sans-serif;">// output : </span><span style="font-family: Arial, Helvetica, sans-serif;">[Pair, Apple, Banana, Orange, Grape]</span>  
  33.     }  
  34.   
  35.     public static void reverse()  
  36.     {  
  37.         Set<String> sortSet = new TreeSet<String>(testStrList);  
  38.         List<String> sortList = new ArrayList<String>(sortSet);  
  39.         Collections.reverse(sortList);  
  40.         System.out.println(sortList);  
  41.         // output : [Pair, Orange, Grape, Banana, Apple]  
  42.     }  
  43.   
  44.     public static void swap()  
  45.     {  
  46.         Set<String> sortSet = new TreeSet<String>(testStrList);  
  47.         List<String> sortList = new ArrayList<String>(sortSet);  
  48.         Collections.swap(sortList, 0, sortList.size() - 1);  
  49.         System.out.println(sortList);  
  50.         output : [Apple, Orange, Grape, Banana, Pair]  
  51.     }  
  52.   
  53.     public static void main(String[] args)  
  54.     {  
  55.         SetUtil.sort();  
  56.         SetUtil.reverse();  
  57.         SetUtil.swap();  
  58.         SetUtil.removeDuplicate();  
  59.     }  
  60. }