Java Streams Api
What are Java 8 streams?
A stream is an iterator whose function is to accept a set of actions and apply them to each of the elements it contains. A stream represents an object sequence from a collection or other source that supports aggregate operations. Unlike collections, iteration logic implements inside the stream.
Also, streams are inherently lazily loaded and processed, unlike collections.
The key interface is java.util.stream.Stream<T>
. It accepts Functional Interfaces so that lambdas can be passed.
What is stream pipelining?
Java Streams Api - Operations
What are the sources of data objects a Stream can process?
A Stream can process the following data:
- A collection of an Array.
- An I/O channel or an input device.
- A reactive source (e.g., comments in social media or tweets/re-tweets)
- A stream generator function or a static factory.
How are Collections different from Stream?
Collections are the source for the Stream. Java 8 collection API is enhanced with the default methods returning Stream<T> from the collections.
Collections | Streams |
---|---|
Data structure holds all the data elements | No data is stored. Have the capacity to process an infinite number of elements on demand |
External Iteration | Internal Iteration |
Can be processed any number of times | Traversed only once |
Elements are easy to access | No direct way of accessing specific elements |
Is a data store | Is an API to process the data |
What is a Spliterator?
The term is a blend of “splittable” and “iterator” and is a new feature in Java SE 8. It is used in Stream API to iterate streams in a parallel or sequential order by internal iteration.
KNOWLEDGE GAP - LEARN MORE
https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html
https://www.baeldung.com/java-spliterator
Explain the difference between predicate and function.
Although they are both functional interfaces, Predicate<T>
is a single argument function that returns either true or false. Function<T,R>
is also a single argument function, although it returns an object instead. In this case, the T
represents the type of function input, and the R
denotes the type of result.
Implementation
- How to convert a List into a Map?
- How to transform a map?
- How to join elements of a List?
- How to use pairs instead of lists or maps?