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


Java TreeSet comparator()用法及代碼示例


java.util.TreeSet.comparator()方法具有設置和返回比較器的重要函數,該比較器可用於對TreeSet中的元素進行排序。如果集合遵循元素的自然排序模式,則該方法返回Null值。

用法:

comp_set = (TreeSet)tree_set.comparator()

參數:該方法不帶任何參數。


返回值:該方法返回用於以特定順序對集合中的元素進行排序的比較器集合。如果集合遵循默認或自然排序模式,則它將返回Null值。

以下程序說明了java.util.TreeSet.comparator()方法的用法:
示例1:使用元素的自然順序時:

// Java code to illustrate comparator() 
import java.util.*; 
  
public class Tree_Set_Demo { 
    public static void main(String[] args) 
    { 
  
        // Creating an empty TreeSet 
        TreeSet<Integer> tree_set = new TreeSet<Integer>(); 
  
        // Adding elemetns to the set 
        tree_set.add(20); 
        tree_set.add(24); 
        tree_set.add(30); 
        tree_set.add(35); 
        tree_set.add(45); 
        tree_set.add(50); 
  
      System.out.println("Tree Set values are: "+ tree_set); 
  
      // Creating a comparator 
      Comparator comp = tree_set.comparator(); 
        
      // Displaying the comparator values 
      System.out.println("Since the Comparator value is: "+ comp); 
      System.out.println("it follows natural ordering"); 
   } 
}
輸出:
Tree Set values are: [20, 24, 30, 35, 45, 50]
Since the Comparator value is: null
it follows natural ordering

示例2:使用特定的比較器時。

// Java code to illustrate the use of comparator() 
import java.util.Comparator; 
import java.util.TreeSet; 
   
class The_Comparator implements Comparator<String> { 
    public int compare(String str1, String str2) 
    { 
        String first_Str; 
        String second_Str; 
        first_Str = str1; 
        second_Str = str2; 
        return second_Str.compareTo(first_Str); 
    } 
} 
   
public class Tree_Set_Demo { 
    public static void main(String[] args) 
    { 
        TreeSet<String> tree_set = new TreeSet<String>(new 
        The_Comparator()); 
   
        tree_set.add("G"); 
        tree_set.add("E"); 
        tree_set.add("E"); 
        tree_set.add("K"); 
        tree_set.add("S"); 
        tree_set.add("4"); 
        System.out.println("Set before using the comparator: "+ 
        tree_set); 
   
        System.out.println("The elements sorted in descending"+ 
        "order:"); 
        for (String element : tree_set) 
            System.out.print(element + " "); 
    } 
}
輸出:
Set before using the comparator: [S, K, G, E, 4]
The elements sorted in descendingorder:
S K G E 4


相關用法


注:本文由純淨天空篩選整理自Chinmoy Lenka大神的英文原創作品 TreeSet comparator() Method in Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。