java.util.TreeSet.comparator()方法具有设置和返回比较器的重要函数,该比较器可用于对TreeSet中的元素进行排序。如果集合遵循元素的自然排序模式,则该方法返回Null值。
用法:
comp_set = (TreeSet)tree_set.comparator()
参数:该方法不带任何参数。
返回值:该方法返回用于以特定顺序对集合中的元素进行排序的比较器集合。如果集合遵循默认或自然排序模式,则它将返回Null值。
以下程序说明了java.util.TreeSet.comparator()方法的用法:
示例1:使用元素的自然顺序时:
// Java code to illustrate comparator()
import java.util.*;
public class Tree_Set_Demo {
public static void main(String[] args)
{
// Creating an empty TreeSet
TreeSet<Integer> tree_set = new TreeSet<Integer>();
// Adding elemetns to the set
tree_set.add(20);
tree_set.add(24);
tree_set.add(30);
tree_set.add(35);
tree_set.add(45);
tree_set.add(50);
System.out.println("Tree Set values are: "+ tree_set);
// Creating a comparator
Comparator comp = tree_set.comparator();
// Displaying the comparator values
System.out.println("Since the Comparator value is: "+ comp);
System.out.println("it follows natural ordering");
}
}
输出:
Tree Set values are: [20, 24, 30, 35, 45, 50] Since the Comparator value is: null it follows natural ordering
示例2:使用特定的比较器时。
// Java code to illustrate the use of comparator()
import java.util.Comparator;
import java.util.TreeSet;
class The_Comparator implements Comparator<String> {
public int compare(String str1, String str2)
{
String first_Str;
String second_Str;
first_Str = str1;
second_Str = str2;
return second_Str.compareTo(first_Str);
}
}
public class Tree_Set_Demo {
public static void main(String[] args)
{
TreeSet<String> tree_set = new TreeSet<String>(new
The_Comparator());
tree_set.add("G");
tree_set.add("E");
tree_set.add("E");
tree_set.add("K");
tree_set.add("S");
tree_set.add("4");
System.out.println("Set before using the comparator: "+
tree_set);
System.out.println("The elements sorted in descending"+
"order:");
for (String element : tree_set)
System.out.print(element + " ");
}
}
输出:
Set before using the comparator: [S, K, G, E, 4] The elements sorted in descendingorder: S K G E 4
相关用法
- Java Stream sorted(Comparator comparator)用法及代码示例
- Java Collectors maxBy(Comparator comparator)用法及代码示例
- Java Collectors minBy(Comparator comparator)用法及代码示例
- Java PriorityBlockingQueue comparator()用法及代码示例
- Java PriorityQueue comparator()用法及代码示例
- Java Comparator reversed()用法及代码示例
- Java Comparator nullsLast()用法及代码示例
- Java ConcurrentSkipListSet comparator()用法及代码示例
- Java Comparator comparingLong()用法及代码示例
- Java Comparator nullsFirst()用法及代码示例
- Java Comparator comparingDouble()用法及代码示例
- Java Comparator thenComparingLong()用法及代码示例
- Java Comparator thenComparingDouble()用法及代码示例
- Java Comparator naturalOrder()用法及代码示例
- Java Comparator reverseOrder()用法及代码示例
注:本文由纯净天空筛选整理自Chinmoy Lenka大神的英文原创作品 TreeSet comparator() Method in Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。