Streams on Arrays in Java 8
Last Updated :
16 Sep, 2022
In this article, we would be going through stream method of Arrays class which is added in Java 8, it simplifies many operations on arrays as well have improved the efficiency.
Addition of different features like lambdas and streams in java 8 have made java efficient to write elegant code which have improve the readability providing increase in efficiency of performance in most case.
Syntax :
public static IntStream stream(int[] arr)
Parameter :
arr - An array which is to be converted to the stream
Returns :
An IntStream of an array
Variations :
public static IntStream stream(int[] array)
public static IntStream stream(int[] array, int startInclusive, int endExclusive)
public static DoubleStream stream(double[] array)
public static DoubleStream stream(double[] array, int startInclusive, int endExclusive)
public static LongStream stream(long[] array)
public static LongStream stream(long[] array, int startInclusive, int endExclusive)
public static Stream stream(T[] array)
public static Stream stream(T[] array, int startInclusive, int endExclusive)
Prerequisite:-
Note: - Even if you are not familiar with these topics, you can go through the article as it uses very basic lambda expression and explains how to use method of stream class.
Let's see an example of streams on Arrays. In this example, we will be finding average over the array elements and will see the difference in way of writing code in imperative and declarative styles
Example 1:
Java
import java.util.Arrays;
class GFG_Demo_1 {
public static void main(String[] args)
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
// Let's try the imperative style first(which we
// are familiar with)
int sum = 0;
for (int i = 0; i < arr.length; i++)
sum += arr[i];
System.out.println("Average using iteration :" +
(sum / arr.length));
// Let's try the declarative style now
sum = Arrays.stream(arr) // Step 1
.sum(); // Step 2
System.out.println("Average using streams : " +
(sum / arr.length));
// forEach()
// It iterates through the entire streams
System.out.println("Printing array elements : ");
Arrays.stream(arr)
.forEach(e->System.out.print(e + " "));
}
}
Output:
Average using iteration :10
Average using streams : 10
Printing array elements :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
In the above example you have seen stream working let’s see what these step does.
Step 1:
Arrays.stream(arr) - In this step we call the stream method on the Arrays class passing arr as the parameter to the function this statement returns IntStream.
Step 2:
Arrays.stream(arr).sum() – Once we get the IntStream we can use different methods of the IntStream interface.
While you go through IntStream. interface documentation you can open each method to see whether it’s perform a terminal operation or intermediate operation. And we should use this method accordingly either at the terminal or in between.
Now let's go through different methods of IntStream and see what operations this methods perform.We will see example of all this methods in contrast of an array..
We will going through the following methods in the example below.
- asDoubleStream()
- asLongStream()
- anyMatch()
- allMatch()
- noneMatch()
Java
import java.util.Arrays;
import java.util.function.IntPredicate;
class GFG_Demo_2 {
public static void main(String[] args)
{
int arr_sample1[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
// asDoubleStream()
// It converts the original array to double
System.out.println("Example of asDoubleStream(): ");
Arrays.stream(arr_sample1)
.asDoubleStream()
.forEach(e->System.out.print(e + " "));
// asLongStream()
// It converts the original array to Long
System.out.println("\nExample of asLongStream");
Arrays.stream(arr_sample1)
.asLongStream()
.forEach(e->System.out.print(e + " "));
int arr_sample2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 23, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
// anyMatch()
// This method find whether the given predicate
// is in the array or not
System.out.println("\nExample of anyMatch");
// Test whether any of the element in array is
// divisible by 11 or not
IntPredicate predicate = e->e % 11 == 0;
System.out.println(Arrays.stream(arr_sample2)
.anyMatch(predicate));
// You can directly write the lambda expression
// which computes to IntPredicate
// Uncomment to test
// System.out.println(Arrays.stream(arr)
// .anyMatch(e -> e % 11 == 0));
int arr_sample3[] = { 2, 4, 6, 8, 10 };
int arr_sample4[] = { 1, 3, 5, 7, 11 };
// allMatch()
// This method finds whether the given predicate
// matches the entire array or not
System.out.println("Example of allMatch :");
// Returns true as all the elements of arr_sample3
// is even
System.out.println(Arrays.stream(arr_sample3)
.allMatch(e->e % 2 == 0));
// Returns false as all the elements of arr_sammple4
// is odd
System.out.println(Arrays.stream(arr_sample4)
.allMatch(e->e % 2 == 0));
// noneMatch()
System.out.println("Example of noneMatch");
System.out.println(Arrays.stream(arr_sample4)
.noneMatch(e->e % 2 == 0));
}
}
Output:
Example of asDoubleStream():
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0
14.0 15.0 16.0 17.0 18.0 19.0 20.0
Example of asLongStream
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Example of anyMatch
false
Example of allMatch :
true
false
Example of noneMatch
true
We have seen very few methods though IntStream provides many more, lets try some more.
We will going through the following methods in the example below.
- average()
- findAny()
- findFirst()
- max()
- min()
- reduce()
Remember all this method returns OptionalInt or OptionalDouble instead of int or double.
Java
import java.util.Arrays;
class GFG_Demo_3 {
public static void main(String[] args)
{
int arr_sample1[] = { 11, 2, 3, 42, 5, 6, 17, 8, 9,
10, 11, 12, 13, 24, 55, 16, 47, 18, 19, 20 };
System.out.println("These method returns Optional");
// average()
// This method returns a average of an array
System.out.println("Example of average() : ");
System.out.println((Arrays.stream(arr_sample1)
.average()));
// findAny()
// It can return any value from the stream
// Most of the time it returns the first value
// but it is not assured it can return any value
System.out.println("Example of findAny() : ");
System.out.println(Arrays.stream(arr_sample1)
.findAny());
// findFirst()
// It returns the first element of the stream
System.out.println("Example of findFirst() :");
System.out.println(Arrays.stream(arr_sample1)
.findFirst());
// max()
// It returns the max element in an array
System.out.println("Example of max() :");
System.out.println(Arrays.stream(arr_sample1)
.max());
// min()
// It returns the min element in an array
System.out.println("Example of min() :");
System.out.println(Arrays.stream(arr_sample1)
.min());
// reduce()
// It reduces the array by certain operation
// Here it performs addition of array elements
System.out.println("Example of reduce() :");
System.out.println(Arrays.stream(arr_sample1)
.reduce((x, y)->x + y));
// reduce() have another variation which we will
// see in different example
}
}
OutputThese method returns Optional
Example of average() :
OptionalDouble[17.4]
Example of findAny() :
OptionalInt[11]
Example of findFirst() :
OptionalInt[11]
Example of max() :
OptionalInt[55]
Example of min() :
OptionalInt[2]
Example of reduce() :
OptionalInt[348]
But it becomes really difficult to work with this OptionalInt and OptionalDouble, hence Java provides method to convert them into double and int values such that it can be easily reused
Java
import java.util.Arrays;
class GFG_Demo_4 {
public static void main(String[] args)
{
int arr_sample1[] = { 11, 2, 3, 42, 5, 6, 17, 8, 9,
10, 11, 12, 13, 24, 55, 16, 47, 18, 19, 20 };
System.out.println("These method convert Optional to primitive");
// OptionalDouble can be converted to double by using getAsDouble()
// if average doesn't contains any value it throws NoSuchElementException
System.out.println("Example of average() : ");
System.out.println((Arrays.stream(arr_sample1)
.average()
.getAsDouble()));
// OptionalInt can be converted to int by using getAsInt()
System.out.println("Example of findAny() : ");
System.out.println(Arrays.stream(arr_sample1)
.findAny()
.getAsInt());
}
}
Output:
These method convert Optional to primitive
Example of average() :
17.4
Example of findAny() :
11
There are some more methods provided by IntStream which we will be going through in different article and would be working with different variations of stream method.
Reference :
https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
Similar Reads
Arrays.stream() Method in Java
Arrays.stream() method is used to get a sequential Stream from the elements of an array passed as a parameter. Below is a simple example that uses Arrays.stream() to convert a String array into a Stream for sequential processing.Example:Java// Java program to demonstrate Arrays.stream() method impor
3 min read
Array to Stream in Java
Prerequisite : Stream In Java Using Arrays.stream() : Syntax : public static <T> Stream<T> getStream(T[] arr) { return Arrays.stream(arr); } where, T represents generic type. Example 1 : Arrays.stream() to convert string array to stream. Java // Java code for converting string array // t
3 min read
String Arrays in Java
A String Array in Java is an array that stores string values. The string is nothing but an object representing a sequence of char values. Strings are immutable in Java, this means their values cannot be modified once created.When we create an array of type String in Java, it is called a String Array
5 min read
Stream In Java
Stream was introduced in Java 8, the Stream API is used to process collections of objects. A stream in Java is a sequence of objects that supports various methods that can be pipelined to produce the desired result. Use of Stream in JavaThe uses of Stream in Java are mentioned below:Stream API is a
7 min read
Arrays in Java
Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
How to Get ArrayList from Stream in Java 8?
Given a Stream, the task is to convert this Stream into ArrayList in Java 8. Examples:Input: Stream: [1, 2, 3, 4, 5]Output: ArrayList: [1, 2, 3, 4, 5]Input: Stream: ['G', 'e', 'e', 'k', 's']Output: ArrayList: ['G', 'e', 'e', 'k', 's']1. Using Collectors.toList() method: Approach:Get the Stream to be
2 min read
Stream sorted() in Java
Stream sorted() returns a stream consisting of the elements of this stream, sorted according to natural order. For ordered streams, the sort method is stable but for unordered streams, no stability is guaranteed. It is a stateful intermediate operation i.e, it may incorporate state from previously s
2 min read
Vector vs ArrayList in Java
ArrayList and Vectors both implement the List interface, and both use (dynamically resizable) arrays for their internal data structure, much like using an ordinary array. Syntax: ArrayList: ArrayList<T> al = new ArrayList<T>(); Vector: Vector<T> v = new Vector<T>(); ArrayList
4 min read
Comparing Streams to Loops in Java
A stream is an ordered pipeline of aggregate operations(filter(), map(), forEach(), and collect()) that process a (conceptually unbounded) sequence of elements. A stream pipeline consists of a source, followed by zero or more intermediate operations; and a terminal operation. An aggregate operation
7 min read
10 Ways to Create a Stream in Java
The Stream API, introduced in Java 8, it is used to process collections of objects. Stream is a sequence of objects, that supports many different methods which can be pipe lined to produce the desired result. The features of Java stream are â A stream is not a data structure alternatively it takes i
9 min read