📜  如何在Java中按降序对 TreeSet 进行排序?

📅  最后修改于: 2022-05-13 01:54:23.872000             🧑  作者: Mango

如何在Java中按降序对 TreeSet 进行排序?

给定Java中的 TreeSet,任务是按降序(降序)对 TreeSet 的元素进行排序。
例子:

Input : Set: [2, 3, 5, 7, 10, 20]
Output : Set: [20, 10, 7, 5, 3, 2]

Input : Set: [computer, for, geeks, hello]
Output : Set: [hello, geeks, for, computer]

方法:
要使 TreeSet 元素按降序排列,只需使用descendingSet()方法,该方法用于以相反的顺序更改 TreeSet 的顺序
下面是上述方法的实现:

Java
// Java Program to print TreeSet in reverse Order
import java.util.TreeSet;
 
public class TreeSetDescending
{
 
    public static void main(String[] args)
    {
        // Declare a treeset
        TreeSet ints = new TreeSet();
        ints.add(2);
        ints.add(20);
        ints.add(10);
        ints.add(5);
        ints.add(7);
        ints.add(3);
 
        // Initialize treeset with
        // predefined set in reverse order
        // using descendingSet()
        TreeSet intsReverse =
            (TreeSet)ints.descendingSet();
 
        // Print the set
        System.out.println("Without descendingSet(): " +
                                                 ints);
        System.out.println("With descendingSet(): " +
                                           intsReverse);
    }
}

输出
Without descendingSet(): [2, 3, 5, 7, 10, 20]
With descendingSet(): [20, 10, 7, 5, 3, 2]