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:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: