java streams tutorial

Spread the love

java streams tutorial

In this in-depth tutorial, we’ll go through the practical usage of Java 8 Streams from creation to parallel execution.

To understand this material, readers need to have a basic knowledge of Java 8 (lambda expressions, Optional, method references) and of the Stream API. If you aren’t familiar with these topics, please take a look at our previous articles – New Features in Java 8 and Introduction to Java 8 Streams.

Further reading:
Lambda Expressions and Functional Interfaces: Tips and Best Practices
Tips and best practices on using Java 8 lambdas and functional interfaces.
Read more →
Guide to Java 8’s Collectors
The article discusses Java 8 Collectors, showing examples of built-in collectors, as well as showing how to build custom collector.
Read more →
2. Stream Creation
There are many ways to create a stream instance of different sources. Once created, the instance will not modify its source, therefore allowing the creation of multiple instances from a single source.

2.1. Empty Stream
The empty() method should be used in case of a creation of an empty stream:

Stream<String> streamEmpty = Stream.empty();
Its often the case that the empty() method is used upon creation to avoid returning null for streams with no element:

public Stream<String> streamOf(List<String> list) {
return list == null || list.isEmpty() ? Stream.empty() :;
2.2. Stream of Collection
Stream can also be created of any type of Collection (Collection, List, Set):

Collection<String> collection = Arrays.asList(“a”, “b”, “c”);
Stream<String> streamOfCollection =;
2.3. Stream of Array
Array can also be a source of a Stream:

Stream<String> streamOfArray = Stream.of(“a”, “b”, “c”);
They can also be created out of an existing array or of a part of an array:

String[] arr = new String[]{“a”, “b”, “c”};
Stream<String> streamOfArrayFull =;
Stream<String> streamOfArrayPart =, 1, 3);
2.4. Stream.builder()
When builder is used the desired type should be additionally specified in the right part of the statement, otherwise the build() method will create an instance of the Stream<Object>:

Stream<String> streamBuilder =
2.5. Stream.generate()

The generate() method accepts a Supplier<T> for element generation. As the resulting stream is infinite, developer should specify the desired size or the generate() method will work until it reaches the memory limit:

Dell Boomi Online Training

java streams tutorial

For More:  Online Training

India|US|UK|Canada|Australia|Germany|Philippines|New Zealand|Switzerland

Mumbai|Kolkata|Bangalore|Chennai|Kerala|Pune|Hyderabad|Lucknow|New Delhi

Scroll to top