Member-only story

Java Streams — Part 2

Top 10 Stream Creation Patterns that you need to be aware of

--

Fig 2.1 Snippet of Stream Creation Patterns used in the article

In the previous article, we have seen what are streams and why the streams are there. In this article, we will see the top 10 Stream creation patterns that we need to be aware of. These patterns come in handy in daily development activities.

Before we begin, let me mention one more point.

Apart from the generic typed interface, the Stream<T>, there are also some primitive streams to work with the streams that represent primitive type values such as IntStream, LongStream, and DoubleStream that represent primitive int, long and double streams respectively.

Now let us have a look at different patterns of building the streams.

Building Streams

There are many patterns of how we can build the streams. A stream-building pattern involves taking data from a particular source. All these patterns are explained below.

Pattern #1: From a Collection object using the stream() method

We can build a stream from a collection just by calling stream() method on that collection object as below.

1a) Building the Stream from a Set:

// A Set of Unique Strings
Set<String> names = ...
// Gives us a stream of unique strings
Stream<String> nameStream = names.stream();

1b) Building the Stream from a List:

// A List of Students
List<Student> students = ...
// Gives us a stream of Students
Stream<Student> studentStream = students.stream();

1c) Building the Stream from a Map:

Building the Stream from a Map object involves a bit of effort. As a Map contains key-value pairs, we need to call keySet() and values() methods individually on the map object to get the Set of keys and List of values respectively. After that, we need to call stream() on each collection as shown below.

// ID to Student Map
Map<Integer, Student> idToStudentMap = ...;
// Getting the Stream using keySet() Student ID Set
Stream<Integer> idStream = idToStudentMap.keySet().stream();

--

--

KRISHNA KISHORE V
KRISHNA KISHORE V

Written by KRISHNA KISHORE V

Full Stack Tech Lead | Software Consultant | Technical Content Writer

No responses yet

Write a response