Custom Sort Set in Java

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.

Comments