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.

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