In  this tutorial, we will see “How to sort an array in Ascending and Descending order using Java 8?”

How to sort an array in Ascending and Descending orders using java 8 streams

Java 8 – How to SORT an Array in Ascending and Descending order using Streams? Share on X

/**
 * Using Java 8, Sort and Array in Ascending and Descending Orders
 * @author Deepak Verma
 *
 */

import java.util.Arrays;

public class Sort_Array_Ascending_Descending_Order_Java8Stream_Example {

	public static void main(String args[]) {
		
		int[] numbers = {2, 7, 5, 4, 1, 9, 3, 6, 8};

        // Sort in the Ascending order
        System.out.println("Array in Ascending Order: ");
        Arrays.stream(numbers)
              .sorted()
              .forEach(n -> System.out.print(n + " "));

        System.out.println("\n");

        // Sort in the Descending order
        System.out.println("Array in Descending Order: ");
        Arrays.stream(numbers)
              .boxed()
              .sorted((x, y) -> y - x)
              .forEach(n -> System.out.print(n + " "));
	}
}

 

Output:

Array in Ascending Order: 
1 2 3 4 5 6 7 8 9 

Array in Descending Order: 
9 8 7 6 5 4 3 2 1 

How to sort an array in Ascending and Descending orders using java 8 streams

Java 8 – How to SORT an Array in Ascending and Descending order using Streams? Share on X

Do you like this Post? – then check my other helpful posts:

Other Useful References:

Author

  • Deepak Verma

    Deepak Verma is a Test Automation Consultant and Software development Engineer for more than 10 years. His mission is to help you become an In-demand full stack automation tester.

    He is also the founder of Techndeck, a blog and online coaching platform dedicated to helping you succeed with all the automation basics to advanced testing automation tricks.

    View all posts