【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. 

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,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。