CodesJava

Easy learning with example program codes

how to sort arraylist using comparator in java?


ArrayList:

ArrayList class extends AbstractList and implements the List interface. It uses dynamic arrays for storing elements. It maintains insertion order. ArrayList can contain duplicate elements. It is not synchronized.

Note: ArrayList provides the facility of random access because of it is index based.

We can use Collections.sort() method to sort arraylist using comparator in java. We have to pass Comparator object in it.

Example:

package com.codesjava;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
 
class Employee{    
    private String name;
    private int salary;
 
    public Employee(String name, int salary){
        this.name = name;
        this.salary = salary;
    }
 
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public String toString(){
        return "Name: "+this.name+", Salary: "+this.salary;
    }
}
 
class SalaryComp implements Comparator<Employee>{	 
    @Override
    public int compare(Employee e1, Employee e2) {
        if(e1.getSalary() < e2.getSalary()){
            return 1;
        } else {
            return -1;
        }
    }
}
 
public class Test {
 public static void main(String args[]){
	List<Employee> list = new ArrayList<Employee>();
        list.add(new Employee("Jai",50000));
        list.add(new Employee("Mahesh",80000));
        list.add(new Employee("Vishal",60000));
        list.add(new Employee("Hemant",64000));
        Collections.sort(list,new SalaryComp());
        System.out.println("Sorted list entries: ");
        for(Employee e:list){
            System.out.println(e);
        }
 }
}

Output

Sorted list entries: 
Name: Mahesh, Salary: 80000
Name: Hemant, Salary: 64000
Name: Vishal, Salary: 60000
Name: Jai, Salary: 50000


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap