當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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