What if you have a specific scenario where you want to first sort by rank and then alphabetically if the ranks are same? | Eklavya Online

What if you have a specific scenario where you want to first sort by rank and then alphabetically if the ranks are same?

Any number of Comparator classes can be created to sort them differently as shown below.

import java.util.Comparator;

 

public class JavaTechnologyComparator implements Comparator<JavaTechnology> {

 

@Override

public int compare(JavaTechnology t1, JavaTechnology t2) {

 

//handle null values here

Integer rank1 = t1.getRank();

Integer rank2 = t2.getRank();

int rankVal = rank1.compareTo(rank2);

int nameVal = t1.getName().toLowerCase().compareTo(t2.getName().toLowerCase());

 

//if same rank, then sort by name

if(rankVal == 0){

return nameVal;

}

//else sort by rank

return rankVal ;

}

}

Now, the Sort3Test class has been slightly modified to use a Comparator.

import java.util.Collections;

import java.util.List;

 

public class Sort3Test {

public static void main(String[] args) {

 

JavaTechnology jt1 = new JavaTechnology(“JEE”, 1);

JavaTechnology jt2 = new JavaTechnology(“Java”, 1);

JavaTechnology jt3 = new JavaTechnology(“Servlets”, 2);

JavaTechnology jt4 = new JavaTechnology(“JSP”, 2);

JavaTechnology jt5 = new JavaTechnology(“JNDI”, 3);

JavaTechnology jt6 = new JavaTechnology(“EJB”, 4);

JavaTechnology jt7 = new JavaTechnology(“JMS”, 5);

 

List<JavaTechnology> values = Arrays.asList(jt1, jt2, jt3, jt4, jt5, jt6, jt7);

 

Collections.sort(values, new JavaTechnologyComparator());

// invokes the compare(…) in JavaTechnologyComparator

// a number of times

System.out.println(values);

}

}

The output will be:

[(Java , 1), (JEE , 1), (JSP , 2), (Servlets , 2), (JNDI , 3), (EJB , 4), (JMS , 5)]

This should now enable you to sort any Java objects.