1. Java 8 Stream
A java Stream is a sequence of elements supporting sequential and parallel aggregate operations. A java 8 stream is to perform operations on collection of elements, which might be an array, a collection, a generator function, an I/O channel, etc. Streams provide a declarative approach to Collections. Java Stream API provides Classes to support functional-style operations on streams of elements, such as map-reduce transformations on collections.
To perform a computation, stream operations are composed into a stream pipeline. A stream pipeline consists of a source, intermediate operations and terminal operations.
1. Source – which might be an array, a collection, a generator function, an I/O channel, etc
2. Intermediate operations– which transform a stream into another stream.
3. Terminal operation– which produces a result or side-effect.
2. Java 8 Stream features :
1. Java Streams are Functional in nature. They work perfectly with lambdas.
2. No storage – Streams don’t store any elements.
3. Consumable- The elements of a stream are only visited once during the life of a stream. They are not reusable.
4. Streams are immutable.
5. Streams are sequential or parallelized.
6. Laziness-seeking – Intermediate operations are always lazy.
3. Java 8 Stream Intermediate operations :
Operation Name and Description |
---|
1.Stream filter(Predicate<? super T> predicate) – Returns a stream consisting of the elements of this stream that match the given predicate. |
2. Stream map(Function<? super T,? extends R> mapper) – Returns a stream consisting of the results of applying the given function to the elements of this stream. |
3. IntStream mapToInt(ToIntFunction<? super T> mapper) – Returns an IntStream consisting of the results of applying the given function to the elements of this stream. |
4. LongStream mapToLong(ToLongFunction<? super T> mapper) – Returns a LongStream consisting of the results of applying the given function to the elements of this stream. |
5. DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) – Returns a DoubleStream consisting of the results of applying the given function to the elements of this stream. |
6. Stream flatMap(Function<? super T,? extends Stream<? extends R>> mapper) – Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) |
7. IntStream flatMapToInt(Function<? super T,? extends IntStream> mapper) – Returns an IntStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) |
8. LongStream flatMapToLong(Function<? super T,? extends LongStream> mapper) – Returns an LongStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream. (If a mapped stream is null an empty stream is used, instead.) |
9. DoubleStream flatMapToDouble(Function<? super T,? extends DoubleStream> mapper) – Returns an DoubleStream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have placed been into this stream. (If a mapped stream is null an empty stream is used, instead.) |
10. Stream distinct() – Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream. |
11. Stream sorted() – Returns a stream consisting of the elements of this stream, sorted according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed. |
12. Stream sorted(Comparator<? super T> comparator) – Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator. |
13. Stream peek(Consumer<? super T> action) – Returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. |
1Stream limit(long maxSize)Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. |
14. Stream skip(long n) – Returns a stream consisting of the remaining elements of this stream after discarding the first n elements of the stream. If this stream contains fewer than n elements then an empty stream will be returned. |
4. Java Stream Terminal operations :
Operation Name and Description |
---|
1. void forEach(Consumer<? super T> action) – Performs an action for each element of this stream. |
2. void forEachOrdered(Consumer<? super T> action) – Performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. |
3. Object[] toArray() – Returns an array containing the elements of this stream. |
4. A[] toArray(IntFunction <A[]> generator) – Returns an array containing the elements of this stream, using the provided generator function to allocate the returned array, as well as any additional arrays that might be required for a partitioned execution or for resizing. |
5. T reduce(T identity, BinaryOperator accumulator) – Performs a reduction on the elements of this stream, using the provided identity value and an associative accumulation function, and returns the reduced value. |
6. Optional reduce(BinaryOperator accumulator) – Performs a reduction on the elements of this stream, using an associative accumulation function, and returns an Optional describing the reduced value, if any. |
7. U reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator combiner) – Performs a reduction on the elements of this stream, using the provided identity, accumulation and combining functions. |
8. R collect(Supplier supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) – Performs a mutable reduction operation on the elements of this stream. A mutable reduction is one in which the reduced value is a mutable result container, such as an ArrayList, and elements are incorporated by updating the state of the result rather than by replacing the result. |
9. <R,A> R collect(Collector<? super T,A,R> collector) – Performs a mutable reduction operation on the elements of this stream using a Collector. A Collector encapsulates the functions used as arguments to collect(Supplier, BiConsumer, BiConsumer), allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning. |
10. Optional max(Comparator<? super T> comparator) – Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.This is a terminal operation. |
11. boolean anyMatch(Predicate<? super T> predicate) – Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated. |
12. long count() – Returns the count of elements in this stream. |
13. boolean allMatch(Predicate<? super T> predicate) – Returns whether all elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. |
14. boolean noneMatch(Predicate<? super T> predicate) – Returns whether no elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then true is returned and the predicate is not evaluated. |
15. Optional<T> findFirst() – Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned. |
16. Optional<T> findAny() Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. |
5. A simple example without java streams :
Printing even numbers from collection without java stream.
public class WithoutStreamsDemo { public static void main(String[] args) { List<Integer> list = Arrays.asList(10,13,5,15,12,20); //Printing even numbers for(Integer i : list) { if(i%2 == 0) System.out.println(i); } } }
5. A simple example with java 8 streams :
Printing even numbers from collection using Java 8 Stream.
public class WithStreamsDemo { public static void main(String[] args) { List<Integer> list = Arrays.asList(10,13,5,15,12,20); list.stream() // Ccreating Stream from collection source .filter(i -> i%2 == 0) // Intermediate Operation .forEach(System.out::println); // Terminal Operation //Output - 10 12 20 } }