java.util.SortedMap接口的comparator()方法用於返回用於對該映射中的鍵進行排序的比較器;如果此映射使用其鍵的自然順序,則返回null。
用法:
public Comparator comparator()
返回值:此方法返回用於對該映射中的鍵進行排序的比較器;如果此映射使用其鍵的自然順序,則返回null。
以下示例程序旨在說明comparator()方法:
範例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 SortedTreeMap
SortedMap<Integer, String>
sotreemap = new TreeMap<Integer, String>();
// Populating tree map
sotreemap.put(1, "one");
sotreemap.put(2, "two");
sotreemap.put(3, "three");
sotreemap.put(4, "four");
sotreemap.put(5, "five");
// Pritnig the SortedTreeMap
System.out.println("SortedTreeMap:" + sotreemap);
// Getting used Comparator in the map
// using comparator() method
Comparator comp = sotreemap.comparator();
// Pritnig the comparator value
System.out.println("Comparator value:"
+ comp);
}
catch (NullPointerException e) {
System.out.println("Exception thrown:" + e);
}
}
}
輸出:
SortedTreeMap:{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<div class = 'outputDiv'>
<b>Output:</b>
<pre>
Initial Mappings are:{10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}
The set is:[10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You]
</pre>
</div>
{
try {
// Creating object of TreeMap
SortedMap<Integer, String>
sotreemap = new TreeMap<Integer, String>(
Collections.reverseOrder());
// Populating tree map
sotreemap.put(1, "one");
sotreemap.put(2, "two");
sotreemap.put(3, "three");
sotreemap.put(4, "four");
sotreemap.put(5, "five");
// Pritnig the TreeMap
System.out.println("SortedTreeMap:" + sotreemap);
// Getting used Comparator in the map
// using comparator() method
Comparator comp = sotreemap.comparator();
// Pritnig the comparator value
System.out.println("Comparator value:" + comp);
}
catch (NullPointerException e) {
System.out.println("Exception thrown:" + e);
}
}
}
輸出:
SortedTreeMap:{5=five, 4=four, 3=three, 2=two, 1=one} Comparator value:java.util.Collections$ReverseComparator@232204a1
相關用法
- Java Collectors maxBy(Comparator comparator)用法及代碼示例
- Java Collectors minBy(Comparator comparator)用法及代碼示例
- Java Stream sorted(Comparator comparator)用法及代碼示例
- Java TreeMap comparator()用法及代碼示例
- Java Comparator naturalOrder()用法及代碼示例
- Java Comparator thenComparingDouble()用法及代碼示例
- Java Comparator thenComparingLong()用法及代碼示例
- Java Comparator comparingLong()用法及代碼示例
- Java Comparator reversed()用法及代碼示例
- Java Comparator nullsLast()用法及代碼示例
- Java Comparator nullsFirst()用法及代碼示例
- Java Comparator thenComparingInt()用法及代碼示例
- Java ConcurrentSkipListSet comparator()用法及代碼示例
- Java Comparator reverseOrder()用法及代碼示例
- Java Comparator comparingDouble()用法及代碼示例
注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 SortedMap comparator() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。