DEV Community

loizenai
loizenai

Posted on

Java 8 Streams

https://grokonez.com/java/java-8/java-8-streams

Java 8 Streams

Java 8 comes with some prominent features like Lambda Expressions, Method References. And Streams are also an important concept that we should comprehend.

This tutorial will help you have a deep view of Java 8 Streams: what they are, ways to create them, how they work with intermediate operations, terminal operation...

I. Overview

1. What is Java 8 Stream?

A stream is an abstract concept that represents a sequence of objects created by a source, it’s neither a data structure nor a collection object where we can store items. So we can't point to any location in the stream, we just interact with items by specifying the functions.

This is an example of a Stream:


List numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// get List from Stream Operation
List result = numbers.stream()
        .filter(i -> (i % 2) == 0)
        .map(i -> "[" + i + "]")
        .collect(Collectors.toList());

System.out.println(result);

Run the code above, the console shows:


[[2], [4], [6], [8]]

Now, we have concept of using a Stream is to enable functional-style operations on streams of elements. Those operations are composed into a stream pipeline which consists of:
Source > Intermediate Operations > Terminal Operation

  • a source (in the example, it is a collection - List, but it is also an array, a generator function, an I/O channel...)
  • intermediate operations (which transform current stream into another stream at the current chain, in the example, filter is the first operation and map is the second one)
  • a terminal operation (which produces a result or side-effect, in the example, it is collect)

More at:

https://grokonez.com/java/java-8/java-8-streams

Java 8 Streams

Top comments (0)