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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。