Master java skills

How to sort an ArrayList using lambda

Functional programming which was introduced in java 8 has made it very easy to sort arraylist using forEach method and lambda expression. Observe the below example

Collections.sort(cList, (c1, c2) -> c1.getName().compareTo(c2.getName()));

You can see that it can be done in just one line. In this example, c1, c2 represent Cricketer class objects and sorting is done on a property called name which is String data type. Refer the full example below.

Cricketer.java

package com.jts;

public class Cricketer {

	private String name;
	private int noOfRuns;

	//getter and setters
	//constructors
	//toString

}

ArraylistSortingExample.java

package com.jts;

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

public class ArraylistSortingExample {
	
	public static void main(String[] args) {
		
		List<Cricketer> cList = new ArrayList<>();
		cList.add(new Cricketer("Virat Kohli", 10000));
		cList.add(new Cricketer("Rohit Sharma", 8000));
		cList.add(new Cricketer("Steven Smith", 8500));
		cList.add(new Cricketer("Kane Williamson", 7000));
		
		System.out.println("Before sorting : " + cList);
		//sorting using lambda
		Collections.sort(cList, (c1, c2) -> c1.getName().compareTo(c2.getName()));
		
		System.out.println("After sorting on name : " + cList);
		
	}
}

Output:

To know more about java8 features, follow the below link