Sunday 1 June 2014

ArrayList : sort(Comparator c) : Sort this List using given Comparator

public void sort(Comparator<? super E> c)
Sorts this list using the supplied Comparator to compare elements.

class Employee{
 Integer number;
 String name;
 
 Employee(int number, String  name){
  this.number = number;
  this.name = name;
 } 
 
 public String toString(){
  return number + " " + name;
 }
}

import java.util.Comparator;
class EmployeeIdComparator implements Comparator<Employee>{

 public int compare(Employee e1, Employee e2){
  return e1.number.compareTo(e2.number);
 }
 
 public String toString(){
  return "EmployeeIdComparator";
 }
}

import java.util.*;

class ArrayListSort{
 public static void main(String args[]){
  ArrayList<Employee> myList;
  EmployeeIdComparator comparator;
  
  myList = new ArrayList<> ();
  comparator = new EmployeeIdComparator();
  
  myList.add(new Employee(2, "xyz"));
  myList.add(new Employee(1, "mno"));
  myList.add(new Employee(5, "abc"));
  myList.add(new Employee(4, "def"));
  myList.add(new Employee(3, "ghi"));
  
  System.out.println("Elements Before Sorting");
  System.out.println(myList); 
  
  myList.sort(comparator);
  
  System.out.println("Elements After Sorting");
  System.out.println(myList); 
 }
}

Output
Elements Before Sorting
[2 xyz, 1 mno, 5 abc, 4 def, 3 ghi]
Elements After Sorting
[1 mno, 2 xyz, 3 ghi, 4 def, 5 abc]


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment