🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
1. Introduction
In Java, sorting a Set collection in a specific order, either ascending or descending, requires more consideration than sorting a List due to the inherent nature of sets not to maintain an order. However, by using a TreeSet and providing a custom Comparator, you can sort a set according to custom-defined rules. This blog post will demonstrate how to sort a Set of custom objects first in ascending order and then in descending order.
2. Program Steps
1. Define a class for storing objects in the set.
2. Create a Set and populate it with instances of the class.
3. Define custom Comparators for ascending and descending order.
4. Create a TreeSet with the custom Comparator to sort in ascending order.
5. Repeat the process with the custom Comparator for descending order.
6. Display the sorted sets.
3. Code Program
import java.util.*;
// Step 1: Defining the class
class Fruit implements Comparable<Fruit> {
String name;
int quantity;
Fruit(String name, int quantity) {
this.name = name;
this.quantity = quantity;
}
@Override
public String toString() {
return name + ": " + quantity;
}
@Override
public int compareTo(Fruit other) {
return this.name.compareTo(other.name);
}
}
public class CustomSortSet {
public static void main(String[] args) {
// Step 2: Creating and populating the set
Set<Fruit> fruits = new HashSet<>();
fruits.add(new Fruit("Apple", 50));
fruits.add(new Fruit("Orange", 20));
fruits.add(new Fruit("Banana", 40));
// Step 3: Defining custom Comparators
Comparator<Fruit> byQuantityAscending = Comparator.comparingInt(f -> f.quantity);
Comparator<Fruit> byQuantityDescending = byQuantityAscending.reversed();
// Step 4: Sorting in ascending order using TreeSet
Set<Fruit> sortedAsc = new TreeSet<>(byQuantityAscending);
sortedAsc.addAll(fruits);
System.out.println("Fruits sorted by quantity (ascending):");
sortedAsc.forEach(System.out::println);
// Step 5: Sorting in descending order using TreeSet
Set<Fruit> sortedDesc = new TreeSet<>(byQuantityDescending);
sortedDesc.addAll(fruits);
System.out.println("\nFruits sorted by quantity (descending):");
sortedDesc.forEach(System.out::println);
}
}
Output:
Fruits sorted by quantity (ascending): Orange: 20 Banana: 40 Apple: 50 Fruits sorted by quantity (descending): Apple: 50 Banana: 40 Orange: 20
Explanation:
1. The Fruit class is defined with name and quantity fields, and implements the Comparable<Fruit> interface to provide a default natural ordering of its instances (by name in this example).
2. A HashSet named fruits is created and populated with Fruit objects. HashSet does not maintain any order.
3. Two Comparator<Fruit> objects, byQuantityAscending and byQuantityDescending, are defined to specify the sorting criteria based on quantity. byQuantityDescending is simply the reversed order of byQuantityAscending.
4. To sort the set in ascending order, a TreeSet is created with byQuantityAscending as its comparator, and all elements from fruits are added. TreeSet automatically sorts its elements according to the comparator.
5. The process is repeated with byQuantityDescending to sort the set in descending order.
6. The sorted sets are printed, demonstrating how the TreeSet and custom Comparators can be used to sort a Set in both ascending and descending order based on custom criteria.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment