Tuesday 6 October 2020

Use of Comparable and Comparator class for sorting ArrayList Objects


Use of Comparable class for sorting ArrayList Objects


package com.test;


import java.util.ArrayList;

import java.util.Collections;

import java.util.List;


class Employee implements  Comparable{

private Integer rollNo;

private String name;

private Integer age;


public Employee(Integer rollNo, String name, Integer age) {

super();

this.rollNo = rollNo;

this.name = name;

this.age = age;

}


@Override

public String toString() {

return "Employee [rollNo=" + rollNo + ", name=" + name + ", age=" + age + "]\n";

}


@Override

public int compareTo(Object o) {  

Employee e = (Employee) o;

return this.rollNo.compareTo(e.rollNo);

}

}


public class Demo {


public static void main(String[] args) {

Employee emp = null;

    List<Employee> list = new ArrayList<Employee>();

    list.add( emp = new Employee(101, "Cheten", 36));

    list.add( emp = new Employee(603, "Brijesh", 29));

    list.add( emp = new Employee(308, "Ajay", 38));

    list.add( emp = new Employee(902, "Mansi", 26));

    list.add( emp = new Employee(327, "sunil", 40));

    list.add( emp = new Employee(206, "Aman", 32));

    list.add( emp = new Employee(490, "vimal", 25));

    Collections.sort(list);

    System.out.println(list);

    

}

}








Use of Comparator class for sorting ArrayList Objects

package com.test;


import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;


class Employee{

public Integer rollNo;

public String name;

public Integer age;


public Employee(Integer rollNo, String name, Integer age) {

super();

this.rollNo = rollNo;

this.name = name;

this.age = age;

}


@Override

public String toString() {

return "Employee [rollNo=" + rollNo + ", name=" + name + ", age=" + age + "]\n";

}

}


public class Demo {


public static void main(String[] args) {

Employee emp = null;

    List<Employee> list = new ArrayList<Employee>();

    list.add( emp = new Employee(101, "Cheten", 36));

    list.add( emp = new Employee(603, "Brijesh", 29));

    list.add( emp = new Employee(308, "Ajay", 38));

    list.add( emp = new Employee(902, "Mansi", 26));

    list.add( emp = new Employee(327, "sunil", 40));

    list.add( emp = new Employee(206, "Aman", 32));

    list.add( emp = new Employee(490, "vimal", 25));

    

  

    Comparator<Employee> com = new Comparator<Employee>() {

@Override

public int compare(Employee o1, Employee o2) {

if(o1.rollNo > o2.rollNo)

return 1;

return -1;

}

    };


    System.out.println("Before sorting by rollNo : \n"+list);

    Collections.sort(list,com);

    System.out.println("After sorting by rollNo : \n"+list);

    

}

}








No comments:

Post a Comment