Java 8 : Sort ArrayList using List sort() method

Prior to JDK 8, we could sort an ArrayList using Collections.sort() method.

JDK 8 added a new sort() method in List that can sort it using a Comparator.

 

List sort() method

The syntax of sort() is :


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

All elements in this list must be mutually comparable using the specified comparator.

If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements’ natural ordering should be used.

 

Sorting using List sort method

In this example, we sort a List of Strings in natural order.

package com.techkatak.app;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ArrayListDemo {

  public static void main(String[] args) {
    List<Integer> numList = new ArrayList<Integer>();
    
    numList.add(15);
    numList.add(10);
    numList.add(55);
    numList.add(20);
    numList.add(25);
    
    System.out.println("Original List elements : " + numList);
  
    numList.sort(null);
    
    System.out.println("Sorted List elements : " + numList);
  }

}


 

Output

Original List elements : [15, 10, 55, 20, 25]
Sorted List elements : [10, 15, 20, 25, 55]

 

Sort ArrayList of custom Objects using sort method

In this example, we will create some Employee objects and sort them based on the employee names.

package com.topjavatutorial;

public class Employee {
  private String empName;
  private long empId;
  
  public Employee(long empId, String empName){
    this.empId = empId;
    this.empName = empName;
  }

  public String getEmpName() {
    return empName;
  }

  public long getEmpId() {
    return empId;
  }
  
  public String toString(){
    return empName;
    
  }
}


 
With Java8, we can use Lambda expression syntax and sort list of employees as :


empList.sort((o1, o2) -> o1.getEmpName().compareTo(o2.getEmpName()));

 
Here is the complete code:

package com.topjavatutorial;

import java.util.ArrayList;
import java.util.List;

public class ArrayListSort {

  public static void main(String[] args) {
    Employee emp1 = new Employee(123,"John Doe");
    Employee emp2 = new Employee(231,"Joy Lobo");
    Employee emp3 = new Employee(231,"Dave Mathias");
    
    List<Employee> empList = new ArrayList<Employee>();
    empList.add(emp1);
    empList.add(emp2);
    empList.add(emp3);
    
    empList.sort((o1, o2) -> o1.getEmpName().compareTo(o2.getEmpName()));

    System.out.println("Sorted List" + empList);
      
  }

}


 

Output

Sorted List[Dave Mathias, John Doe, Joy Lobo]

 

© 2016, https:. All rights reserved. On republishing this post, you must provide link to original post

One comment

  1. […] Java 8 : Sort ArrayList using List sort() method […]

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: