Introduction
Java 8 introduced the Stream API, which allows developers to process collections of data in a functional and declarative manner. One of the common tasks is to create streams from arrays, enabling you to perform operations such as filtering, mapping, and reducing on the elements of an array. Streams provide a more concise and readable way to handle array data, transforming it into a sequence of elements that can be processed in parallel or sequentially.
In this guide, we’ll explore how to create streams from arrays in Java 8, covering both primitive and object arrays, and demonstrate how to use these streams to perform various operations.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Creating Streams from Object Arrays
- Creating Streams from Primitive Arrays
- Performing Operations on Streams Created from Arrays
- Advanced Considerations
- Conclusion
Problem Statement
The task is to create a Java program that:
- Demonstrates how to create streams from arrays.
- Performs basic operations on the streams created from arrays.
- Outputs the results of these operations.
Example 1:
- Input: Array of integers
[1, 2, 3, 4, 5]
- Output: Stream operations to filter even numbers
[2, 4]
Example 2:
- Input: Array of strings
["apple", "banana", "cherry"]
- Output: Stream operations to convert strings to uppercase
["APPLE", "BANANA", "CHERRY"]
Solution Steps
- Create an Array: Start with an array of elements (either objects or primitives).
- Convert the Array to a Stream: Use the
Arrays.stream()
orStream.of()
methods to convert the array to a stream. - Perform Stream Operations: Apply operations such as filtering, mapping, or reducing on the stream.
- Display the Result: Print the results of the stream operations.
Java Program
Creating Streams from Object Arrays
Creating a stream from an array of objects (e.g., strings or custom objects) is straightforward using the Stream.of()
or Arrays.stream()
methods.
import java.util.Arrays;
import java.util.stream.Stream;
/**
* Java 8 - Creating Streams from Object Arrays
* Author: https://www.rameshfadatare.com/
*/
public class StreamFromObjectArray {
public static void main(String[] args) {
// Step 1: Create an array of strings
String[] fruitArray = {"apple", "banana", "cherry"};
// Step 2: Convert the array to a stream
Stream<String> fruitStream = Arrays.stream(fruitArray);
// Step 3: Perform operations on the stream (convert to uppercase)
fruitStream.map(String::toUpperCase)
.forEach(System.out::println);
}
}
Output
APPLE
BANANA
CHERRY
Explanation
- The
Arrays.stream(fruitArray)
method converts the array of strings into a stream. - The
map(String::toUpperCase)
method transforms each string to its uppercase equivalent. - The
forEach(System.out::println)
method prints each element of the stream.
Creating Streams from Primitive Arrays
Java provides specialized streams for primitive types like int
, long
, and double
. These streams are more efficient than the generic Stream<T>
when working with large amounts of primitive data.
import java.util.Arrays;
import java.util.stream.IntStream;
/**
* Java 8 - Creating Streams from Primitive Arrays
* Author: https://www.rameshfadatare.com/
*/
public class StreamFromPrimitiveArray {
public static void main(String[] args) {
// Step 1: Create an array of integers
int[] numberArray = {1, 2, 3, 4, 5};
// Step 2: Convert the array to an IntStream
IntStream numberStream = Arrays.stream(numberArray);
// Step 3: Perform operations on the stream (filter even numbers)
numberStream.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}
Output
2
4
Explanation
- The
Arrays.stream(numberArray)
method converts the array of integers into anIntStream
. - The
filter(n -> n % 2 == 0)
method filters out odd numbers, keeping only even numbers. - The
forEach(System.out::println)
method prints each element of the filtered stream.
Performing Operations on Streams Created from Arrays
After converting arrays to streams, you can perform various operations such as filtering, mapping, sorting, and reducing.
import java.util.Arrays;
import java.util.stream.Stream;
/**
* Java 8 - Performing Operations on Streams Created from Arrays
* Author: https://www.rameshfadatare.com/
*/
public class StreamOperationsFromArray {
public static void main(String[] args) {
// Step 1: Create an array of strings
String[] fruitArray = {"apple", "banana", "cherry"};
// Step 2: Convert the array to a stream
Stream<String> fruitStream = Arrays.stream(fruitArray);
// Step 3: Perform operations on the stream (filter and sort)
fruitStream.filter(fruit -> fruit.length() > 5)
.sorted()
.forEach(System.out::println);
}
}
Output
banana
cherry
Explanation
- The
filter(fruit -> fruit.length() > 5)
method filters the stream to include only strings with more than 5 characters. - The
sorted()
method sorts the filtered elements alphabetically. - The
forEach(System.out::println)
method prints each sorted element.
Advanced Considerations
-
Parallel Streams: If you are working with large arrays and need to process elements in parallel, consider using
Arrays.stream(array).parallelStream()
to improve performance. -
Handling Null Values: When creating streams from arrays that might contain null values, ensure your stream operations handle these nulls appropriately to avoid
NullPointerException
. -
Immutable Arrays: Streams are inherently immutable. If you need to modify the original array, you must collect the stream back into a new array or list.
Conclusion
This guide provides methods for creating streams from arrays in Java 8, covering object arrays, primitive arrays, and performing operations on these streams. Converting arrays to streams allows for more flexible and readable data processing, leveraging the full power of the Stream API. By understanding how to create and manipulate streams from arrays, you can simplify your data processing tasks in Java.