Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:34:06 Viewed : 236
The Stream API is a significant addition to Java introduced in Java 8. It provides a powerful and functional approach to processing sequences of elements, allowing developers to express complex data manipulation operations more concisely and effectively. Streams enable developers to write code that is both readable and parallelizable.
Here are key concepts and an introduction to the Stream API:
Creating Streams:
javaList<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
// Creating a stream from a list
Stream<String> myStream = myList.stream();
Intermediate Operations:
java// Filter elements starting with `c` and convert to uppercase
List<String> result = myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.collect(Collectors.toList());
Terminal Operations:
java// Print elements starting with `c`
myList.stream()
.filter(s -> s.startsWith("c"))
.forEach(System.out::println);
The Stream API supports parallel processing, allowing operations to be executed concurrently and potentially improving performance for large datasets.
javaList<String> result = myList.parallelStream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.collect(Collectors.toList());
Conciseness and Readability:
Parallelization:
Pipelining:
Reduction Operations:
reduce()
, collect()
) that allow you to perform computations on the elements of a stream and produce a result.javaList<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
// Filter, map, and collect in a single pipeline
List<String> result = myList.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.collect(Collectors.toList());
System.out.println(result);
// Output: [C2, C1]
In this example, the Stream API is used to filter elements starting with `c`, convert them to uppercase, and collect the result into a new list.
The Stream API is a powerful tool for modern Java developers, promoting functional programming principles and making code more expressive and concise. It is particularly beneficial when working with large datasets and parallel processing.