Stream API
The Stream API introduced in Java 8 provides a more efficient and concise way to process collections of data.
Java Stream API allows you to perform various operations such as filtering, mapping, reducing, and collecting on collection objects.
To begin using the Stream API, you first need to create a stream from a collection or an array. You can then apply various stream operations to process the elements of the stream.
Let's take a look at an example using the Stream API:
1import java.util.ArrayList;
2import java.util.List;
3
4public class StreamExample {
5
6 public static void main(String[] args) {
7 List<String> fruits = new ArrayList<>();
8 fruits.add("Apple");
9 fruits.add("Banana");
10 fruits.add("Orange");
11
12 // Stream API example
13 fruits.stream()
14 .filter(fruit -> fruit.length() > 5)
15 .forEach(System.out::println);
16 }
17}
In this example, we have a list of fruits and we want to filter out the fruits whose names have more than 5 characters. Using the Stream API, we can easily achieve this by chaining the filter()
operation followed by the forEach()
operation.
The filter()
operation takes a lambda expression as an argument and returns a new stream that contains only the elements that match the given condition. In this case, we filter out the fruits whose length is greater than 5.
The forEach()
operation then iterates over the filtered stream and performs an action on each element. In this case, we print each filtered fruit to the console.
By using the Stream API, we can write more expressive and concise code to process collections of data, making our code more readable and maintainable.
xxxxxxxxxx
import java.util.ArrayList;
import java.util.List;
public class StreamExample {
public static void main(String[] args) {
List<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
// Stream API example
fruits.stream()
.filter(fruit -> fruit.length() > 5)
.forEach(System.out::println);
}
}