Home> Java> javaTutorial> body text

How to sort a TreeSet in descending order in Java?

藏色散人
Release: 2019-04-01 17:48:30
Original
3026 people have browsed it

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]
Copy after login

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 ints = new TreeSet(); ints.add(2); ints.add(20); ints.add(10); ints.add(5); ints.add(7); ints.add(3); TreeSet intsReverse = (TreeSet)ints.descendingSet(); // Print the set System.out.println("Without descendingSet(): " + ints); System.out.println("With descendingSet(): " + intsReverse); } }
        
Copy after login

Output:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!