Sorting User Defined Objects in ArrayList

In our earlier posts we have seen post on how to sort Interger arraylist and how to sort String arraylist. Now we will see how to sort user defined objects in arraylist.To understand this topic, lets create a Employee object with a property empName. I have also overridden the toString method so that i can able to understand the printed content in the console.


package ArrayList;

public class Employee{

String empName;
public Employee(String empName) {
// TODO Auto-generated constructor stub
this.empName = empName;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}

public String toString(){
return empName;
}
}

Now am going to create a class to add some employee objects and to sort those employee objects.


package ArrayList;

import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class ArrayListObjectSort {

public static void main(String[] args) {

Employee employeess1 = new Employee("LEARN");
Employee employeess2 = new Employee("FROM");
Employee employeess3 = new Employee("EXAMPLES");
Employee employeess4 = new Employee("SHIDHAR");
Employee employeess5 = new Employee("learn");
Employee employeess6 = new Employee("from");
Employee employeess7 = new Employee("examples");
Employee employeess8 = new Employee("shidhar");

System.out.println("*****************************************************");
List<Employee> employees2 = new ArrayList<>();
employees2.add(employeess1);
employees2.add(employeess2);
employees2.add(employeess3);
employees2.add(employeess4);
employees2.add(employeess5);
employees2.add(employeess6);
employees2.add(employeess7);
employees2.add(employeess8);
System.out.println("Employee Object before sorting :"+employees2);
Collections.sort(employees2);
System.out.println("Employess Object after sorting :" +employees2);
}
}

When we run the above program we will get some compilation error like this. Because we will not able to sort User defined objects like Strings Or any other Wrapper class(Integer, Double, etc..)


Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Bound mismatch: The generic method sort(List<T>) of type Collections is not applicable for the arguments (List<Employee>). The inferred type Employee is not a valid substitute for the bounded parameter <T extends Comparable<? super T>>

at ArrayList.ArrayListObjectSort.main(ArrayListObjectSort.java:40)

So in order to avoid this error, we have to pass a comparator object (i.e new ArrayListComparator()) in sort method.


package ArrayList;

import java.sql.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

public class ArrayListObjectSort {

public static void main(String[] args) {

Employee employeess1 = new Employee("LEARN");
Employee employeess2 = new Employee("FROM");
Employee employeess3 = new Employee("EXAMPLES");
Employee employeess4 = new Employee("SHIDHAR");
Employee employeess5 = new Employee("learn");
Employee employeess6 = new Employee("from");
Employee employeess7 = new Employee("examples");
Employee employeess8 = new Employee("shidhar");

System.out.println("*****************************************************");
List<Employee> employees2 = new ArrayList<>();
employees2.add(employeess1);
employees2.add(employeess2);
employees2.add(employeess3);
employees2.add(employeess4);
employees2.add(employeess5);
employees2.add(employeess6);
employees2.add(employeess7);
employees2.add(employeess8);
System.out.println("Employees Object before sorting :"+employees2);
Collections.sort(employees2, new ArrayListComparator());
System.out.println("Employees Object after sorting :" +employees2);
}
}

In ArrayListComparator, i implemented Comparator interface and overriden the compareTo method to perform the sorting.


package ArrayList;

import java.util.Comparator;

import HashMap.HashMapEmployee;

public class ArrayListComparator implements Comparator<Employee>{

public ArrayListComparator() {
// TODO Auto-generated constructor stub
}

@Override
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
//less = -1, greater = 1, equal = 0
return (o1.getEmpName() .compareTo(o2.getEmpName())<1 ) ? -1: (o1.getEmpName() .compareTo(o2.getEmpName())>1) ? 1:0 ;

}
}

If we run the project, we will get an output like this.


*****************************************************
Employees Object before sorting :[LEARN, FROM, EXAMPLES, SHIDHAR, learn, from, examples, shidhar]
Employees Object after sorting :[EXAMPLES, FROM, LEARN, SHIDHAR, examples, from, learn, shidhar]

 

If you notice the above code, you can see the output is  care about CASE_SENSITIVE, because it internally  compare based on starting character ASCII value of a String and perform sorting. So in order to avoid that in compareTo method, we have to perform a operation like this.


package ArrayList;

import java.util.Comparator;

import HashMap.HashMapEmployee;

public class ArrayListComparator implements Comparator<Employee>{

public ArrayListComparator() {
// TODO Auto-generated constructor stub
}

@Override
public int compare(Employee o1, Employee o2) {
// TODO Auto-generated method stub
//less = -1, greater = 1, equal = 0
return (o1.getEmpName().toLowerCase() .compareTo(o2.getEmpName().toLowerCase())<1 ) ? -1: (o1.getEmpName().toLowerCase() .compareTo(o2.getEmpName().toLowerCase())>1) ? 1:0 ;

}
}

If you the above code you can see that i converted the empName to lowercase before comparing with other empName. So that our sorting mechanism will take care of CASE_SENSITIVE. So if we run the project, we will get an output like this.


*****************************************************
Employees Object before sorting :[LEARN, FROM, EXAMPLES, SHIDHAR, learn, from, examples, shidhar]
Employees Object after sorting :[examples, EXAMPLES, from, FROM, learn, LEARN, shidhar, SHIDHAR]

Now we will see how to reverse the sorting for User defined Objects

package ArrayList;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListObjectSort {

 public static void main(String[] args) {

 Employee employeess1 = new Employee("LEARN");
 Employee employeess2 = new Employee("FROM");
 Employee employeess3 = new Employee("EXAMPLES");
 Employee employeess4 = new Employee("SHIDHAR");
 Employee employeess5 = new Employee("learn");
 Employee employeess6 = new Employee("from");
 Employee employeess7 = new Employee("examples");
 Employee employeess8 = new Employee("shidhar");

 System.out.println("*****************************************************");
 List<Employee> employees2 = new ArrayList<>();
 employees2.add(employeess1);
 employees2.add(employeess2);
 employees2.add(employeess3);
 employees2.add(employeess4);
 employees2.add(employeess5);
 employees2.add(employeess6);
 employees2.add(employeess7);
 employees2.add(employeess8);
 System.out.println("Employees Object before sorting in reverse direction :"+employees2);
 Collections.sort(employees2, Collections.reverseOrder(new ArrayListComparator()));
 System.out.println("Employees Object after sorting in reverse direction:" +employees2);
 }
}

And the output will be like this

*****************************************************
Employees Object before sorting in reverse direction :[LEARN, FROM, EXAMPLES, SHIDHAR, learn, from, examples, shidhar]
Employees Object after sorting in reverse direction:[shidhar, SHIDHAR, learn, LEARN, from, FROM, examples, EXAMPLES]

If you ArrayListComparator class we have implemented Compartor interface, we can also use Comparable interface to do sorting. Later in our post we will implement sorting using Comparable interface also. Also we will see the difference between Comparable and Comparator interface.

Leave a comment

Your email address will not be published. Required fields are marked *