by @kodeazy

Jav How to create custom comparator using enum to define custom sort order?

Home » java » Jav How to create custom comparator using enum to define custom sort order?
  • To understand how `comparator works click here
  • In this blog we will be discussing about how to sort data based on user requiremnet using comparator with the help of enum.
  • For Example if we want to sort cars data based on color of the car like data having pink color cars to be arranged first and then later with silver color to be arranged next
  • To do these kind of sortings we use enum.

    public enum PaintColors {
    PINK,SILVER, RED,GREEN,YELLOW
    }
  • In the above enum class we arranged PINK first followed by SILVER and so on…
  • Natural order of enum is the order in which the values are declared.
  • So that when we sort the data using Collections.sort(carList,new ColorComparator()); method will sort the data based on how data is arranged in enum.
import java.util.*;
 
class ColorComparator implements Comparator<CarDetails>
 {
     public int compare(CarDetails c1, CarDetails c2)
     {
         return c1.paintColor.compareTo(c2.paintColor);
     }
 }
class CarDetails 
{
     public enum PaintColors {
    PINK,SILVER, RED,GREEN,YELLOW
}
  
    private String carName;
    PaintColors paintColor;

    public CarDetails(String carName, PaintColors color){
        this.carName = carName;
         this.paintColor = color;
    }

    public int compareTo(CarDetails c) {
        return carName.compareTo(c.carName);
    }

    public static void main(String[] args) {
        List<CarDetails> carList = new ArrayList<>();

        carList.add(new CarDetails("Skoda",PaintColors.GREEN));
        carList.add(new CarDetails("Tesla",PaintColors.PINK));
        carList.add(new CarDetails("Honda",PaintColors.SILVER));
        Collections.sort(carList,new ColorComparator());

        carList.forEach(carslist->System.out.println(carslist.paintColor)
        );
          
    }
}

Output:

PINK
SILVER
GREEN

Hence the data is arranged in the way how enum class variables are arranged.