Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
How to Sort TreeSet Elements using Comparable Interface in Java?
Next article icon

How to Sort TreeSet Elements using Comparable Interface in Java?

Last Updated : 01 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

TreeSet is an implementation of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a Set using their natural ordering whether an explicit comparator is provided.

To sort TreeSet elements using Comparable interface in java first, we create a class Student that implements the Comparable interface. In this class we override the compareTo() method.

Pseudo Code:

// Student class implements comparable interface  class Student implements Comparable<Student> {     Integer marks;      Student(Integer marks) {         this.marks = marks;     }      // override toString method     public String toString() {         return (" " + this.marks);     }      // Override compareTo method to sort LinkedHashSet in ascending order     public int compareTo(Student stu) {         return this.marks.compareTo(stu.marks);     } }

Below is the implementation of the above approach:

Example 1:

Java
// Java program to demonstrate how to Sort TreeSet using // Comparable interface in ascending order  import java.util.*;  // Student class implements comparable interface class Student implements Comparable<Student> {        Integer marks;      Student(Integer marks) { this.marks = marks; }      // override toString method     public String toString() { return (" " + this.marks); }      // Override compareTo method to sort TreeSet in     // ascending order     public int compareTo(Student stu)     {         return this.marks.compareTo(stu.marks);     } }  class GFG {     public static void main(String[] args)     {          // New TreeSet         TreeSet<Student> set = new TreeSet<>();          // Adding elements to the set         set.add(new Student(500));         set.add(new Student(300));         set.add(new Student(400));         set.add(new Student(100));         set.add(new Student(200));          // Print TreeSet sorted in ascending order         System.out.println("Sort elements in ascending order : " + set);            } } 

Output
Sort elements in ascending order : [ 100,  200,  300,  400,  500]

Example 2: 

Java
// Java program demonstrate how to Sort TreeSet using // Comparable interface in descending order  import java.util.*;  // Student class implements comparable interface class Student implements Comparable<Student> {        Integer marks;      Student(Integer marks) { this.marks = marks; }      // override toString method     public String toString() { return (" " + this.marks); }      // Override compareTo method to sort TreeSet in     // descending order     public int compareTo(Student stu)     {         return stu.marks.compareTo(this.marks);     } }  class GFG {     public static void main(String[] args)     {          // New TreeSet         TreeSet<Student> set = new TreeSet<>();          // Adding elements to the set         set.add(new Student(500));         set.add(new Student(300));         set.add(new Student(400));         set.add(new Student(100));         set.add(new Student(200));          // Print TreeSet sorted in descending order         System.out.println("Sort elements in descending order : " + set);            } } 

Output
Sort elements in descending order : [ 500,  400,  300,  200,  100]

 
 


Next Article
How to Sort TreeSet Elements using Comparable Interface in Java?

K

KapilChhipa
Improve
Article Tags :
  • Java
  • Java Programs
  • Java-Collections
  • java-treeset
  • Java-Comparable
Practice Tags :
  • Java
  • Java-Collections

Similar Reads

    How to Sort Vector Elements using Comparable Interface in Java?
    Vector is a child interface of collection. If we want to represent a group of the individual objects as a single entity where duplicates are allowed and insertion order must be preserved then we should go for vector. It is a resizable or growable array. It implements a Serializable, Cloneable, and R
    5 min read
    How to Sort HashSet Elements using Comparable Interface in Java?
    The HashSet class implements the Set interface, backed by a hash table which is actually a HashMap instance. No guarantee is made as to the iteration order of the set which means when we iterate the HashSet, there is no guarantee that we get elements in which order they were inserted. To sort HashSe
    3 min read
    How to Sort LinkedHashSet Elements using Comparable Interface in Java?
    The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements
    3 min read
    How to Create TreeMap Objects using Comparable Interface in Java?
    In Java, the TreeMap class is an implementation of the SortedMap interface that stores key-value pairs in a sorted order based on the natural ordering of the keys. By default, the keys are sorted in ascending order. If you want to sort the keys based on a custom ordering criteria, you can use the Co
    6 min read
    How to Iterate Over the Elements in a TreeSet in Natural Order in Java?
    In Java, to iterate over the elements of a TreeSet in their Natural Order, one must either use a custom comparator provided or traverse the elements in ascending order based on their natural ordering. A TreeSet in Java keeps up with its components in arranged requests. In this article, we will learn
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences