How To Sort An Array With Stream API In Java 8 | Java 8 Examples | Java Inspires



 Hi Guys,

Welcome to Java Inspires..

In this post, we will see how to sort an array with Stream API in Java 8.

How To Sort An Array With Stream API In Java 8 | Java 8 Examples | Java Inspires


Java8Example.java

package com.javainspires.java8example;

import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;

/**
 * 
 * @author Java Inspires
 *
 */
public class Java8Example {

	public static void main(String[] args) {

		// define int array
		int[] intArr = { 99, 46, 26, 88, 01, 6, 46, 5 };
		// print array before sort
		System.out.println("Before Sort");
		System.out.println(Arrays.toString(intArr));
		System.out.println();
		// convert the array to stream , here int stream
		IntStream arrayStream = Arrays.stream(intArr);
		// sort using sort method from stream
		arrayStream = arrayStream.sorted();
		// convert stream to array
		intArr = arrayStream.toArray();
		// print array after sort
		System.out.println("After Sort");
		System.out.println(Arrays.toString(intArr));
	}

}

Output:

Before Sort
[99, 46, 26, 88, 1, 6, 46, 5]

After Sort
[1, 5, 6, 26, 46, 46, 88, 99]

Thank You


Post a Comment

Previous Post Next Post