当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java TreeMap comparator()用法及代码示例


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


相关用法


注:本文由纯净天空筛选整理自RohitPrasad3大神的英文原创作品 TreeMap comparator() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。