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());   … Read more

Can you write a simple program that compares two objects to return if they are equal or not? This method will be handy in defining your own equals( ) method.

This is usefull in domain or value object class to compare different object fields in an equals method public class DomainObject {   //protected because only inheriting domain classes can use it protected boolean isPropertyEqual(Object compare1, Object compare2) { // go here if compare1 is null, i.e. test cases 1 & 3 if (compare1 == … Read more

Now, what if you have your own custom class like a Dog, Cat, etc instead of a library class like String, Integer, etc?

Here is an example of a JavaTechnology custom object that implements a default sorting logic based on the rank (i.e popularity). public class JavaTechnology implements Comparable<JavaTechnology>{   private String name; private int rank;   // popularity lower value means more popular   public JavaTechnology(String name, int rank){ this.name = name; this.rank = rank; }   //default … Read more

Is there anything wrong with the above code?

Yes, 2 things — firstly, the above sort is case sensitive, that is the uppercase takes priority over lowercase pushing ‘Java’ after ‘JSP’. Secondly, if the collection had any null values, it will throw a NullpointerException. These two issues can be rectified by providing a custom sorting implementation that ignores case and handles null values … Read more

Can you write code to sort the following string values naturally (i.e. in alphabetical order)? (JEE, Java, Servlets, JMS, JNDI, JDBC, JSP, and EJB)

Here is the sample code that makes use of the default compareTo( ) provided in the String class as it implements the Comparable interface and the Collections utility class that provides a sorting method, which internally uses the efficient “merge sort” algorithm. import java.util.Arrays; import java.util.Collections; import java.util.List;   public class Sort1 { public static … Read more