Collections class has a method Sort which is used to sort arraylist. If List contains String,int... we can use first method. If the List contains Object type we have to use second method to sort List. The Second method has parameter of type Comparator which compare the object by compare(Object o1, Object o2) method Example import java.util.ArrayList; public class JavaApplication1 { Employee emp2=new Employee("Name 2", 18000, "Junior Developer"); Employee emp3=new Employee("Name 3", 48000, "Manager"); Employee emp4=new Employee("Name 4", 30000, "TeamLead"); @Override public Employee(String name, int salary, String designation) { public String getName() { public void setName(String name) { public int getSalary() { public void setSalary(int salary) { public String getDesignation() { public void setDesignation(String designation) { Output Before Sorting....
sort(List<T> list)
sort(List<T> list, Comparator<? super T> c)
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public static void main(String[] args) {
ArrayList<Employee>listEmp=new ArrayList();
Employee emp1=new Employee("Name 1", 20000, "Associate Developer");
listEmp.add(emp1);
listEmp.add(emp2);
listEmp.add(emp3);
listEmp.add(emp4);
System.out.println("Before Sorting....");
for(int k=0;k<listEmp.size();k++)
System.out.println("Emp "+listEmp.get(k).name+" : Salary = "+listEmp.get(k).salary);
Collections.sort(listEmp, new Comparator<Employee>() {
public int compare(Employee o1, Employee o2) {
if (o1.getSalary()==o2.getSalary()) {
return 0;
} else if (o1.getSalary()>o2.getSalary()) {
return 1;
} else {
return -1;
}
}
});
System.out.println("After Sorting....");
for(int k=0;k<listEmp.size();k++)
System.out.println("Emp "+listEmp.get(k).name+" : Salary = "+listEmp.get(k).salary);
}
}
class Employee {
String name;
int salary;
String designation;
this.name = name;
this.salary = salary;
this.designation = designation;
}
return name;
}
this.name = name;
}
return salary;
}
this.salary = salary;
}
return designation;
}
this.designation = designation;
}
}
Emp Name 1 : Salary = 20000
Emp Name 2 : Salary = 18000
Emp Name 3 : Salary = 48000
Emp Name 4 : Salary = 30000
After Sorting....
Emp Name 2 : Salary = 18000
Emp Name 1 : Salary = 20000
Emp Name 4 : Salary = 30000
Emp Name 3 : Salary = 48000
How to Convert a Map to a List in Java Example
What is Difference Between "==" and "equals" method in Java
How to Sort ArrayList of Object Type in Java?
How to join Multiple String Objects in Java 8
How to Fetch System UUID with Java Program?
Java Thread - How to create Threads in Java?
How to create Arraylist from Array in Java
How to convert ArrayList to Array in Java
What is a Collection ?
How to split a string in Java
What is Java Collections Framework?
What is difference between HashMap and HashSet in Java