Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to Sort list of objects by multiple fields in java

  • In order to compare objects we have comparable and comparator in java.
  • If you want to do custom sorting we will use comparator in java
  • We need to use different comparators for sorting objects by different fields.
  • And using Collections.sort(List, Comparator).
  • We can sort list of class objects by using cmparator.
  • By this we can compare two objects field by field. actually many.
  • Lets see an example program to sort list of student objects by name rollno and marks using comparator. Here comparator means we need to develop sorting logic in separate class which implements comparator interface and overrides compare() method.  
Program 1: Write a java example program to sort list of objects 

Student class:

  • Define a class as student add variables.
  • Define a constructor to assign values to variables.
  • Define a toString() method to print each variable value inside object values when we print object.

  1. package com.sortobjects;
  2. /**
  3.  * How to sort list of class objects
  4.  * @author www.instanceofjava.com
  5.  */
  6.  
  7. public class Student {
  8.     
  9.     String name;
  10.     int Rollno;
  11.     float marks;
  12.  
  13. Student(String name, int Rollno, float marks){
  14.         
  15.         this.name=name;
  16.         this.marks=marks;
  17.         this.Rollno=Rollno;
  18. }
  19.  
  20.     public String getName() {
  21.         return name;
  22.     }
  23.     public void setName(String name) {
  24.         this.name = name;
  25.     }
  26.     public int getRollno() {
  27.         return Rollno;
  28.     }
  29.     public void setRollno(int rollno) {
  30.         Rollno = rollno;
  31.     }
  32.     public float getMarks() {
  33.         return marks;
  34.     }
  35.     public void setMarks(float marks) {
  36.         this.marks = marks;
  37.     }
  38.     
  39. public String toString() {
  40.         return ("Name:"+name+"\tRollNo:"+Rollno+"\tMarks"+marks);
  41.     }
  42.  
  43. }

 NameComparator:

  • This class sort list of student class objects by name.

  1. package com.sortobjects;
  2. import java.util.Comparator;
  3.  
  4. public class NameComparator implements Comparator{
  5.     /**
  6.      * How to sort list of class objects
  7.      * @author www.instanceofjava.com
  8.      */
  9.     @Override
  10.     public int compare(Student obj1, Student obj2) {
  11.      
  12.          return obj1.getName().compareTo(obj2.getName());
  13.     }
  14.    
  15.  
  16. }

 RollNoComparator :
  • This class sort list of student class objects by Rollno.


  1. package com.sortobjects;
  2. import java.util.Comparator;
  3.  
  4. public class RollNoComparator implements Comparator{
  5.     /**
  6.      * How to sort list of class objects
  7.      * @author www.instanceofjava.com
  8.      */
  9.     @Override
  10.     public int compare(Student obj1, Student obj2) {
  11.      
  12.          return ((Integer)obj1.getRollno()).compareTo((Integer)obj2.getRollno());
  13.     }
  14.    
  15.  
  16. }

MarksComparator:
  • This class will compare list of student class objects by marks

  1. package com.sortobjects;
  2. import java.util.Comparator;
  3. public class MarksComparator implements Comparator{
  4.     /**
  5.      * How to sort list of class objects
  6.      * @author www.instanceofjava.com
  7.      */
  8.     @Override
  9.     public int compare(Student obj1, Student obj2) {
  10.          return ((Float)obj1.getMarks()).compareTo((Float)obj2.getMarks());
  11.     }
  12.  
  13. }

SortListObjects:
  •  Take a test class 
  • Create arraylist object and add Student objects with different values into list.
  • Using Collections.Sort(List,FiledComparator) pass corresponding comparator class in order to sort multiple fields of a class.


  1. package com.sortobjects;
  2. mport java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5.  
  6. /**
  7.  * How to sort list of class objects
  8.  * @author www.instanceofjava.com
  9.  */
  10.  
  11. public class SortListObjects {
  12.  
  13.      public static void main(String[] args){
  14.         
  15.         
  16.         List studentlst= new ArrayList();
  17.         
  18.         studentlst.add(new Student("Saisesh",1,80));
  19.         studentlst.add(new Student("Vinod",2,90));
  20.         studentlst.add(new Student("Ajay",3,95));
  21.         
  22.         System.out.println("** Before sorting **:");
  23.          
  24.         for (Student student : studentlst) {
  25.             System.out.println(student);
  26.         }
  27.         Collections.sort(studentlst,new NameComparator());
  28.         
  29.         System.out.println("** After sorting **");
  30.          
  31.         for (Student student : studentlst) {
  32.             System.out.println(student);
  33.         }
  34.     }
  35.  
  36. }
 Output:





  •  Like this we can compare list of objects by Rollno, and marks aslo. Please practice this example by sorting rollno and marks and check output. if you have any doubts then leave a comment.

 Chained comparator:
  • We can use chained comparator to sort list of class objects by multiple fields by passing multiple comparators.
  • java collections sort multiple comparators
  • The below program is example of chained comparator java


  1. package com.sortobjects;
  2.  
  3. import java.util.Arrays;
  4. import java.util.Comparator;
  5. import java.util.List;
  6.  
  7. public class StudentChainedComparator implements Comparator {
  8.     
  9.      private List> listComparators;
  10.      
  11.     
  12.         public StudentChainedComparator(Comparator... comparators) {
  13.             this.listComparators = Arrays.asList(comparators);
  14.         }
  15.      
  16.         @Override
  17.         public int compare(Student student1, Student student2) {
  18.             for (Comparator comparator : listComparators) {
  19.                 int result = comparator.compare(student1, student2);
  20.                 if (result != 0) {
  21.                     return result;
  22.                 }
  23.             }
  24.             return 0;
  25.         }
  26.  
  27.        
  28.  
  29. }
 
Java comparator multiple fields example:


  • Lets see an example of java comparatorchain in java





This post first appeared on Java Tutorial - InstanceOfJava, please read the originial post: here

Share the post

How to Sort list of objects by multiple fields in java

×

Subscribe to Java Tutorial - Instanceofjava

Get updates delivered right to your inbox!

Thank you for your subscription

×