Category : Java | Sub Category : Java8 Features | By Prasad Bonam Last updated: 2023-11-13 04:41:44 Viewed : 223
In the Java Stream API, operations can be classified into two main categories: intermediate operations and terminal operations.
Intermediate operations transform a stream into another stream. They are lazy, meaning they dont execute until a terminal operation is invoked. Intermediate operations allow you to create a pipeline of operations to be performed on the elements of a stream. Here are some common intermediate operations:
filter(Predicate<T> predicate)
:
javaList<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");
List<String> result = myList.stream()
.filter(s -> s.startsWith("c"))
.collect(Collectors.toList());
// Result: [c2, c1]
map(Function<T, R> mapper)
:
javaList<String> result = myList.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
// Result: [A1, A2, B1, C2, C1]
flatMap(Function<T, Stream<R>> mapper)
:
javaList<List<String>> nestedList = Arrays.asList(
Arrays.asList("a1", "a2"),
Arrays.asList("b1", "c2", "c1")
);
List<String> result = nestedList.stream()
.flatMap(List::stream)
.collect(Collectors.toList());
// Result: [a1, a2, b1, c2, c1]
distinct()
:
javaList<String> result = myList.stream()
.distinct()
.collect(Collectors.toList());
// Result: [a1, a2, b1, c2, c1]
sorted()
and sorted(Comparator<T> comparator)
:
javaList<String> result = myList.stream()
.sorted()
.collect(Collectors.toList());
// Result: [a1, a2, b1, c1, c2]
Terminal operations produce a result or a side effect. After a terminal operation is invoked, the stream is consumed, and it cannot be reused. Here are some common terminal operations:
forEach(Consumer<T> action)
:
javamyList.stream()
.forEach(System.out::println);
// Prints each element of the stream
collect(Collector<T, A, R> collector)
:
Collector
.javaList<String> result = myList.stream()
.filter(s -> s.startsWith("c"))
.collect(Collectors.toList());
// Result: [c2, c1]
reduce(T identity, BinaryOperator<T> accumulator)
and reduce(BinaryOperator<T> accumulator)
:
javaOptional<String> concatenated = myList.stream()
.reduce((s1, s2) -> s1 + s2);
// Result: Optional[a1a2b1c2c1]
count()
:
long
.javalong count = myList.stream()
.count();
// Result: 5
anyMatch(Predicate<T> predicate)
, allMatch(Predicate<T> predicate)
, and noneMatch(Predicate<T> predicate)
:
javaboolean anyStartsWithA = myList.stream().anyMatch(s -> s.startsWith("a"));
// Result: true
boolean allStartWithA = myList.stream().allMatch(s -> s.startsWith("a"));
// Result: false
boolean noneStartsWithZ = myList.stream().noneMatch(s -> s.startsWith("z"));
// Result: true
findFirst()
and findAny()
:
Optional
.javaOptional<String> firstElement = myList.stream().findFirst();
// Result: Optional[a1]
These are some common intermediate and terminal operations in the Stream API. Combining these operations allows developers to write expressive and concise code for data processing.