码迷,mamicode.com
首页 > 编程语言 > 详细

【DataStructure】Charming usage of Set in the java

时间:2014-07-18 14:02:00      阅读:282      评论:0      收藏:0      [点我收藏+]

标签:java   set   

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

标签:java   set   

原文地址:http://blog.csdn.net/sxb0841901116/article/details/37914033

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!