Stream API in Java
In Java, Stream was introduced in Java 8, the Stream API is used to process collections of objects in a functional and declarative style. A stream is a sequence of objects that supports various methods. A Stream is not a data structure; it just takes input from Collections, Arrays or I/O channels.
Streams do not modify the original data ; they only produce results using their methods. Mainly used for filtering, mapping, reducing, and collecting data, often replacing traditional loop-based approaches.
Syntax:
Stream<T> stream;
Here, T is either a class, object or data type depending upon the declaration.
Key Concepts of the Stream API:
Intermediate Operations: These operations transform a stream into another stream. They are typically lazy, they don't process data until a terminal operation is invoked.
Terminal Operations: These operations produce a result. Once a terminal operation is called, the stream cannot be reused. Examples include forEach(), collect(), reduce(), count(), min(), max(), findFirst().
Intermediate Operations in Java:
1. map() is an intermediate operation. These operations are always lazy.
An object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.
Syntax:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
2. filter(): The filter method is used to select elements as per the Predicate passed as an argument.
Syntax:
Stream<T> filter(Predicate<? super T> predicate)
3. sorted(): The sorted method is used to sort the stream elements.
Syntax:
Stream<T> sorted()
Stream<T> sorted(Comparator<? super T> comparator)
4. flatMap(): The flatMap operation in Java Streams is used to flatten a stream of collections into a single stream of elements.
Syntax:
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
5. distinct(): Removes duplicate elements. It returns a stream consisting of the distinct elements.
Syntax:
Stream<T> distinct()
6. peek(): Performs an action on each element without modifying the stream. It returns a stream consisting of the elements of this stream.
Syntax:
Stream<T> peek(Consumer<? super T> action)
Terminal Operations in Java:
Terminal Operations are the type of Operations that returns only result. These Operations are not processed further just return a final result value on stream.
1. collect(): The collect method is used to return the result of the intermediate operations performed on the stream.
Syntax:
<R, A> R collect(Collector<? super T, A, R> collector)
2. forEach(): The forEach method is used to iterate every element of the stream.
Syntax:
void forEach(Consumer<? super T> action)
3. reduce(): The reduce method is used to reduce the elements of a stream to a single value.
Syntax:
T reduce(T identity, BinaryOperator<T> accumulator)
Optional<T> reduce(BinaryOperator<T> accumulator)
4. count(): Returns the count of elements in the stream.
Syntax:
long count()
5. findFirst(): Returns the first element of the stream.
Syntax:
Optional<T> findFirst()
6. allMatch(): Checks if all elements of the stream match a given predicate.
Syntax:
boolean allMatch(Predicate<? super T> predicate)
7. anyMatch(): Checks if any element of the stream matches a given predicate.
Syntax:
boolean anyMatch(Predicate<? super T> predicate)
Example Java Program:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamApiExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("Alice", "Bob", "Charlie", "David", "Eve");
// Filter names starting with 'A' and convert to uppercase
List<String> filteredAndMappedNames = names.stream()
.filter(name -> name.startsWith("A")) // Intermediate operation: filter
.map(String::toUpperCase) // Intermediate operation: map
.collect(Collectors.toList()); // Terminal operation: collect
System.out.println(filteredAndMappedNames); // Output: [ALICE]
}
}
*Disclaimer: We have published the above images and information for reference purpose only, for any changes on the content we refer to visit the Official Website to get the latest info.
NOTE: Free Career Hub Employees will not call any candidates towards Job Offer or Job assistance. We never charge any candidates for Jobs. Please be aware of fraudulent Calls or Emails.
NOTE: Free Career Hub Employees will not call any candidates towards Job Offer or Job assistance. We never charge any candidates for Jobs. Please be aware of fraudulent Calls or Emails.
Stream API in Java?