Blog Detail

  • Home
  • Java 8 Sorting Array

Java 8 Sorting Array

Sorting collection of elements in java using stream

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

Write a comment