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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。