Home  >  Article  >  Java  >  How to sort a TreeSet in descending order in Java?

How to sort a TreeSet in descending order in Java?

藏色散人
藏色散人Original
2019-04-01 14:40:283091browse

Given a TreeSet in Java, the task is to sort the elements of the TreeSet in descending order (decreasing order).

Example:

输入: Set: [2, 3, 5, 7, 10, 20]
输出: Set: [20, 10, 7, 5, 3, 2]

输入: Set: [computer, for, geeks, hello]
输出: Set: [hello, geeks, for, computer]

Method:

To generate TreeSet elements in order, just use the descendingSet() method, which is used to change in reverse order The order of TreeSet

The following is the implementation of the above method:

import java.util.TreeSet; 
  
public class TreeSetDescending { 
  
    public static void main(String[] args) 
    { 
        // 声明一个treeset
        TreeSet<Object> ints = new TreeSet<Object>(); 
        ints.add(2); 
        ints.add(20); 
        ints.add(10); 
        ints.add(5); 
        ints.add(7); 
        ints.add(3); 
  
        TreeSet<Object> intsReverse = (TreeSet<Object>)ints.descendingSet(); 
  
        // Print the set 
        System.out.println("Without descendingSet(): " + ints); 
        System.out.println("With descendingSet(): " + intsReverse); 
    } 
}

Output:

Without descendingSet(): [computer, for, geeks, hello]
With descendingSet(): [hello, geeks, for, computer]

Related recommendations: "Java Tutorial

This article is about the method of sorting TreeSet in descending order in Java. I hope it will be helpful to friends in need!

The above is the detailed content of How to sort a TreeSet in descending order in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Java Basics: VariablesNext article:Java Basics: Variables