首页 > 代码库 > 【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
- 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();
- }
- }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。