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


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