Tuesday, 10 October 2017

Different ways to sort Array list in Java

In this post, I am going to explain how to sort an array list in Java in different ways.

a.   By using the sort method provided by List interface
b.   By using Collections.sort method
c.   Sort elements using streams

By using sort method of List interface
List interface introduces the sort method from Java1.8 onwards. To make the List interface backward compatible, it made the sort method as default.

default void sort(Comparator<? super E> c)

sort method takes a comparator as argument and sort the list as per the comparator implementation.
 emps.sort(new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });


Above snippet sort employees based on country.

If you pass the comparator as null, then sort method takes the natural ordering of elements. Natural ordering takes the comparable method implementation.

emps.sort(null);

Above snippet sort the elements based on Comparable implementation of Employee class.

Find the below complete working application.


Employee.java
package com.sample.model;

public class Employee implements Comparable<Employee> {

 private int id;
 private String name;
 private String country;

 public Employee(int id, String name, String country) {
  super();
  this.id = id;
  this.name = name;
  this.country = country;
 }

 public int getId() {
  return id;
 }

 public void setId(int id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCountry() {
  return country;
 }

 public void setCountry(String country) {
  this.country = country;
 }

 @Override
 public String toString() {
  return "Employee [id=" + id + ", name=" + name + ", country=" + country + "]";
 }

 @Override
 public int compareTo(Employee emp) {
  if (emp == null)
   return 1;
  return this.id - emp.id;
 }

}


Test.java
package com.sample.sort;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  emps.sort(new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });

  emps.stream().forEach(System.out::println);

  System.out.println("\nSince comparator is not provided, it takes comparable implementation");
  System.out.println("*********************************");
  emps.sort(null);
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=3, name=Krishna, country=Germany]
Employee [id=6, name=Harini, country=India]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=5, name=Bomma, country=UK]
Employee [id=1, name=Kiran, country=USA]

Since comparator is not provided, it takes comparable implementation
*********************************
Employee [id=1, name=Kiran, country=USA]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=5, name=Bomma, country=UK]
Employee [id=6, name=Harini, country=India]

java.util.Collections class provided sort method to sort elements of list.

public static <T extends Comparable<? super T>> void sort(List<T> list)
public static <T> void sort(List<T> list,Comparator<? super T> c)

First form of sort method sorts the elements in their natural ordering, for ex: for integers ascending order is the natural order. You can specify the natural
ordering of elements by implementing Comparable interface.


Below snippet sort the elements based on employee country.
  Collections.sort(emps, new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });

Below snippet sort the elements by natural ordering.

Collections.sort(emps);

Find the below working application.


Test.java
package com.sample.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  Collections.sort(emps, new Comparator<Employee>() {

   @Override
   public int compare(Employee emp1, Employee emp2) {
    return emp1.getCountry().compareToIgnoreCase(emp2.getCountry());
   }

  });

  emps.stream().forEach(System.out::println);

  System.out.println("\nSince comparator is not provided, it takes comparable implementation");
  System.out.println("*********************************");
  Collections.sort(emps);
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=3, name=Krishna, country=Germany]
Employee [id=6, name=Harini, country=India]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=5, name=Bomma, country=UK]
Employee [id=1, name=Kiran, country=USA]

Since comparator is not provided, it takes comparable implementation
*********************************
Employee [id=1, name=Kiran, country=USA]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=5, name=Bomma, country=UK]
Employee [id=6, name=Harini, country=India]


If you do not specify the comparator, then sort method sort the elements based on the Comparable implementation.

Below snippet sort the elements based on the Comparable implementation of Employee class.
Collections.sort(emps, null);


Test.java
package com.sample.sort;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  Collections.sort(emps, null);
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=1, name=Kiran, country=USA]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=5, name=Bomma, country=UK]
Employee [id=6, name=Harini, country=India]

c. Sort elements using streams
Below snippet sort the elements using country of the employee.
emps.stream().sorted(comparing(Employee::getCountry)).collect(Collectors.toList());


Test.java
package com.sample.sort;

import static java.util.Comparator.comparing;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.sample.model.Employee;

public class Test {
 public static void main(String args[]) {
  Employee emp1 = new Employee(6, "Harini", "India");
  Employee emp2 = new Employee(1, "Kiran", "USA");
  Employee emp3 = new Employee(5, "Bomma", "UK");
  Employee emp4 = new Employee(3, "Krishna", "Germany");
  Employee emp5 = new Employee(2, "Rama Krishna", "India");

  List<Employee> emps = Arrays.asList(emp1, emp2, emp3, emp4, emp5);

  System.out.println("Employees before sorting");
  System.out.println("*********************************");
  emps.stream().forEach(System.out::println);

  System.out.println("\nEmployees after sort by country");
  System.out.println("*********************************");
  emps = emps.stream().sorted(comparing(Employee::getCountry)).collect(Collectors.toList());
  emps.stream().forEach(System.out::println);

 }
}


Output
Employees before sorting
*********************************
Employee [id=6, name=Harini, country=India]
Employee [id=1, name=Kiran, country=USA]
Employee [id=5, name=Bomma, country=UK]
Employee [id=3, name=Krishna, country=Germany]
Employee [id=2, name=Rama Krishna, country=India]

Employees after sort by country
*********************************
Employee [id=3, name=Krishna, country=Germany]
Employee [id=6, name=Harini, country=India]
Employee [id=2, name=Rama Krishna, country=India]
Employee [id=5, name=Bomma, country=UK]
Employee [id=1, name=Kiran, country=USA]




No comments:

Post a Comment