java.util.TreeMap類的comparator()方法用於返回用於對該映射中的鍵進行排序的比較器;如果此映射使用其鍵的自然順序,則返回null。
用法:
public Comparator comparator()
返回值:此方法返回用於對該映射中的鍵進行排序的比較器;如果此映射使用其鍵的自然順序,則返回null
以下示例說明了descendingIterator()方法
範例1:對於自然排序
// Java program to demonstrate
// comparator() method for natural ordering
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of TreeMap
NavigableMap<Integer, String>
treemap = new TreeMap<Integer, String>();
// populating tree map
treemap.put(1, "one");
treemap.put(2, "two");
treemap.put(3, "three");
treemap.put(4, "four");
treemap.put(5, "five");
// pritnig the TreeMap
System.out.println("TreeMap:" + treemap);
// getting used Comparator in the map
// using comparator() method
Comparator comp = treemap.comparator();
// pritnig the comparator value
System.out.println("Comparator value:"
+ comp);
}
catch (NullPointerException e) {
System.out.println("Exception thrown:" + e);
}
}
}
輸出:
TreeMap:{1=one, 2=two, 3=three, 4=four, 5=five} Comparator value:null
範例2:反向排序
// Java program to demonstrate
// comparator() method
// for reverse ordering
import java.util.*;
public class GFG1 {
public static void main(String[] argv)
throws Exception
{
try {
// creating object of TreeMap
NavigableMap<Integer, String>
treemap = new TreeMap<Integer, String>(
Collections.reverseOrder());
// populating tree map
treemap.put(1, "one");
treemap.put(2, "two");
treemap.put(3, "three");
treemap.put(4, "four");
treemap.put(5, "five");
// pritnig the TreeMap
System.out.println("TreeMap:" + treemap);
// getting used Comparator in the map
// using comparator() method
Comparator comp = treemap.comparator();
// pritnig the comparator value
System.out.println("Comparator value:" + comp);
}
catch (NullPointerException e) {
System.out.println("Exception thrown:" + e);
}
}
}
輸出:
TreeMap:{5=five, 4=four, 3=three, 2=two, 1=one} Comparator value:java.util.Collections$ReverseComparator@232204a1
輸出:
Comparator value:java.util.Collections$ReverseComparator@232204a1
相關用法
- Java Collectors maxBy(Comparator comparator)用法及代碼示例
- Java Collectors minBy(Comparator comparator)用法及代碼示例
- Java Stream sorted(Comparator comparator)用法及代碼示例
- Java Comparator reversed()用法及代碼示例
- Java Comparator comparingLong()用法及代碼示例
- Java Comparator nullsFirst()用法及代碼示例
- Java ConcurrentSkipListSet comparator()用法及代碼示例
- Java Comparator reverseOrder()用法及代碼示例
- Java SortedMap comparator()用法及代碼示例
- Java Comparator nullsLast()用法及代碼示例
- Java Comparator thenComparingInt()用法及代碼示例
- Java Comparator naturalOrder()用法及代碼示例
- Java Comparator thenComparingDouble()用法及代碼示例
- Java Comparator thenComparingLong()用法及代碼示例
- Java Comparator comparingDouble()用法及代碼示例
注:本文由純淨天空篩選整理自RohitPrasad3大神的英文原創作品 TreeMap comparator() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。