Sort the ArrayList in Java 8

In this blog, we can see how to sort the arraylist in java 8. Before that you can see what is sorting and its types. What should keep in your mind before you apply it in your code.

We can apply the sorting only on collection. That collection may be a list, set or map. We can perform two different types of sorting 1 is Ascending order and 2nd is Descending order. You to follow below points when you have to decide to sort the element in the collection.

  • Which type of data you have in collection
  • Based on which property or variable you are going to sort.
  • define implementation of Comparable or Comparater based on your requirement

In this sample code, we have array list, its having the Integer data. and we are going to sort that arraylist in ascending and descending order with the help of a Java 8 stream function

package com.samplecoder.streams;

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

public class SortingArray {

	public static void main(String[] args) {
		// TODO Auto-generated method stub

		List<Integer> intNumbers = Arrays.asList(100,3,200,2,1,23,43,545,232);
		
		System.out.println("Way 1");
		intNumbers.stream().sorted().forEach(System.out::println);
		
		System.out.println("\n Way 2 \n");
		intNumbers.stream().sorted((num1, num2) -> num1.compareTo(num2)).forEach(System.out::println);
		
		//Reverse Order
		Collections.sort(intNumbers, Collections.reverseOrder());
		System.out.println("\n Way 3 : Reverse Order \n");
		intNumbers.forEach(System.out::println);
		
	}

}

Result

Way 1
1
2
3
23
43
100
200
232
545

 Way 2 

1
2
3
23
43
100
200
232
545

 Way 3 : Reverse Order 

545
232
200
100
43
23
3
2
1