How to sort list of objects in java with examples

We could achieve list of objects sorting in java by using sort() method which is available under Collections class as well as by using Comparable and Comparator interfaces. Comparable and Comparator are two interfaces in java used to sort list of objects. These interfaces are available under java.util package along with Collections class and other classes and interfaces.

Comparable interface contains the method of 

     public int compareTo(Object obj)

Comparator interface contains the method of 

     public int compare(Object obj1, Object obj2)

The compare() and compareTo() methods will return negative integer(-1), or zero(0) or positive integer(1). When the first obj1 is less than obj2 method will return negative integer. When obj1 is equals to obj2 will return zero and when obj1 is grater than obj2 it will return positive integer.

If it's objects are stored in any Collection classes like ArrayList, HashSet in Array and that time we need to use compare() or compareTo() methods to sort.

If you see the logical difference between these two interfaces is Comparator in java compare two objects passing them into compare() method. Comparable interface compare one object with another providing object into compareTo() method.

If any class implements Comparable interface in java then collection of that object either List or an Array can be sorted by using Array.sort() or Collections.sort() then objects will get save based on their natural order defined by compareTo() method.

Now, we will see how to compare List<Employee> objects based on their lName field.

Sorting by using Comparable interface: 
First, we need to create Employee.java class with fname and lname two fields.

Employee.java 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package com.javatbrains.compare;

class Employee implements Comparable<Object>{
    
    String fname;
    String lname;
    public Employee(String fname, String lname) {
        super();
        this.fname = fname;
        this.lname = lname;
    }
   
    public String getFname() {
        return fname;
    }
    public String getLname() {
        return lname;
    }

    public int compareTo(Object obj){
     Employee person=(Employee) obj;
        return this.lname.compareTo(person.getLname());
    }
}

Then we have write EmployeeComparable class which will prints the result by executing the main() method.

EmployeeComparable.java 
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.javatbrains.compare;

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

public class EmployeeComparable {
    
    public static void main(String[] args) {
       
        List<Employee> emp = new ArrayList<Employee>();
       
        emp.add(new Employee("Subba","Reddy"));
        emp.add(new Employee("Samba","Siva"));
        emp.add(new Employee("Nalla","Machu"));
       
        Collections.sort(emp);
       
        for (Employee e:emp){
            System.out.println(e.getFname()+" "+e.getLname());
        }
    }
}

Output:
Nalla Machu
Subba Reddy
Samba Siva

Sorting by using Comparator interface:
Now, I am going to create one more Employee.java class with name and age fields,

Employee.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
package com.javatbrains.compare;

class Employee{
    
    String firstname;
    Integer age;
    public Employee(String firstname, Integer age) {
        super();
        this.firstname = firstname;
        this.age = age;
    }
   
    public String getFirstname() {
        return firstname;
    }
    public Integer getAge() {
        return age;
    }
}

Then I am going to create TestComparator.java class which was implemented with Comparator interface.

TestComparator.java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.javatbrains.compare;

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

public class TestComparator implements Comparator<Object> {

    public int compare(Object obj1, Object obj2){
        Employee p1=(Employee) obj1;
        Employee p2=(Employee) obj2;
       
        String p1name=p1.getFirstname()+" "+p1.getAge();
        String p2name=p2.getFirstname()+" "+p2.getAge();
       
        return p1name.compareTo(p2name);
    }

    public static void main(String[] args) {
         List <Employee> elist= new ArrayList<Employee>();
       
         elist.add(new Employee("Arvind",25));
         elist.add(new Employee("Arvind",15));
         elist.add(new Employee("Arvind",20));
       
         Collections.sort(elist, new TestComparator());
       
         for(Employee e:elist){
             System.out.println(e.firstname+ " "+e.getAge());
         }
    }
   
}

Output:
Arvind 15
Arvind 20
Arvind 25

Comments

Popular posts from this blog

Hibernate auto increment with example

how to count the page views by using JSP

Multithreading in java with example

How to retrieve data from table by using JDBC with example

Prime, Fibonacci and Factorial number with example in java

How to insert images into database using JDBC?

String interview questions and answers

Exception in thread "main" java.lang.NoClassDefFoundError: javax/transaction/SystemException

Store file into table by using JDBC with example