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.
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.TreeSet; public class SetUtil { public static List<String> testStrList = Arrays.asList("Apple", "Orange", "Pair", "Grape", "Banana", "Apple", "Orange"); /** * Gets sorted sets which contains no duplicate elements * * @time Jul 17, 2014 7:58:16 PM * @return void */ public static void sort() { Set<String> sortSet = new TreeSet<String>(testStrList); System.out.println(sortSet); // output : [Apple, Banana, Grape, Orange, Pair] } public static void removeDuplicate() { Set<String> uniqueSet = new HashSet<String>(testStrList); System.out.println(uniqueSet); <span style="font-family: Arial, Helvetica, sans-serif;">// output : </span><span style="font-family: Arial, Helvetica, sans-serif;">[Pair, Apple, Banana, Orange, Grape]</span> } public static void reverse() { Set<String> sortSet = new TreeSet<String>(testStrList); List<String> sortList = new ArrayList<String>(sortSet); Collections.reverse(sortList); System.out.println(sortList); // output : [Pair, Orange, Grape, Banana, Apple] } public static void swap() { Set<String> sortSet = new TreeSet<String>(testStrList); List<String> sortList = new ArrayList<String>(sortSet); Collections.swap(sortList, 0, sortList.size() - 1); System.out.println(sortList); output : [Apple, Orange, Grape, Banana, Pair] } public static void main(String[] args) { SetUtil.sort(); SetUtil.reverse(); SetUtil.swap(); SetUtil.removeDuplicate(); } }
【DataStructure】Charming usage of Set in the java,布布扣,bubuko.com
【DataStructure】Charming usage of Set in the java
原文地址:http://blog.csdn.net/sxb0841901116/article/details/37914033