当前位置:   article > 正文

使用TreeSet和Comparator,写TreeSetTest1 要求:对TreeSet中的元素"HashSet"、"ArrayList"、"TreeMap"、 "HashMap"、"...

3. 使用treeset和comparator,编写treesettest类,要求对treeset中的元素"hashset

 

import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

/*
* 使用TreeSet和Comparator,写TreeSetTest1
* 要求:对TreeSet中的元素"HashSet"、"ArrayList"、"TreeMap"、
* "HashMap"、"TreeSet"、"LinkedList"进行升序和倒序排列
*/

public class TreeTest1 {
public static void main(String[] args) {
Set<String> treeSet = new TreeSet<>(new Comparator<String>() {//Comparator用compare方法
@Override
public int compare(String o1, String o2) {//compare方法用compareTo比较去返回
return o1.compareTo(o2);
}
});
treeSet.add("HashSet");
treeSet.add("ArrayList");
treeSet.add("TreeMap");
treeSet.add("HashMap");
treeSet.add("TreeSet");
treeSet.add("LinkedList");
System.out.println("按升序排列:");
for (String string : treeSet) {
System.out.print(string+" ");
}
System.out.println();

Set<String> set1 = new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
set1.add("HashSet");
set1.add("ArrayList");
set1.add("TreeMap");
set1.add("HashMap");
set1.add("TreeSet");
set1.add("LinkedList");
System.out.println("按降序排列:");
for(String ele:set1) {
System.out.print(ele+" ");
}
}
}

 

 

转载于:https://www.cnblogs.com/xinchen01/p/10974722.html

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/766154
推荐阅读
相关标签
  

闽ICP备14008679号