Saturday, August 14, 2021

Java 8: Stream API for collections Introduction

Streams Introduction:

These are classes to support functional style operations on streams of elements. Streams are different than collections in following ways

1. Storage: It is not a data structure, it conveys elements from a source hence it does not require any storage

2. Functional: An operation on streams does not modify the source, rather it generates new stream e.g. filter()

3. Laziness Seeking: Intermediate operations in streams are always lazy; invoked only if required for terminal operation

4. Unbounded: Infinite streams can even be converted to finite using operations like limit(n) or findFirst()

5. Consumable: One element of a stream cannot be revisited twice in a lifetime of a stream. If needs to be revisited, new stream should be created

A few different ways to create streams

1. Using stream() or parallelStream() methods on Collection

2. Arrays.stream(Object [])

3. Static factory methods like Stream.of(Object[]) or IntStream.range(int, int)


Stream operations are divided in 2 stages

Intermediate: Returns a new stream and are lazy; it can be stateless (filter, map) or stateful (sorted, distinct) i.e. stateful operations may need to process entire data before producing the result i.e. in case of parallel computations, we might require multiple passes or significant buffering

Terminal: Operations that produces result or a side effect e.g. forEach, map

Intermediate Operations : map(), filter(), distinct(), sorted(), limit(), skip()

Terminal Operations : forEach(), toArray(), reduce(), collect(), min(), max(), count(), anyMatch(), allMatch(), noneMatch(), findFirst(), findAny()

Unless the source of the stream is concurrent, data interference (modifying data) during stream processing can cause exceptions or incorrect results. Stream execution begins when terminal operation is involved and ends when terminal operation is completed.

Hence in below example, result will be printed as 1 2 3 4 (Note: 4 is added after stream creation)

List<Integer> intList = new ArrayList<Integer>(Arrays.asList(1, 2, 3));

Stream<Integer> s = intList.stream();

intList.add(4);

s.forEach(a -> System.out.print(a+" "));


Also check Stream examples for each of the intermediate & terminal Stream operations.

No comments:

SpringBoot: Features: SpringApplication

Below are a few SpringBoot features corresponding to SpringApplication StartUp Logging ·          To add additional logging during startup...