Core Java

Java 8 Stream Intermediate Operations (Methods) Examples

A Complete guide to Java 8 Streams intermediate operations. List of all built-in Stream API Intermediate operations(methods) with examples.

1. Overview

In this tutorial, We’ll learn about What are Intermediate Operations in Java 8 Stream. All these operations are in package java.util.stream.Stream.

In the last tutorial, We’ve discussed Java 8 Stream API and Lambda Expressions.

Rules:

Java 8 Stream intermediate operations return another Stream which allows you to call multiple operations in the form of a query.


Stream intermediate operations do not get executed until a terminal operation is invoked.

All Intermediate operations are lazy, so they’re not executed until a result of processing is actually needed.

Traversal of the Stream does not begin until the terminal operation of the pipeline is executed.

Here is the list of all Stream intermediate operations:

filter()
map()
flatMap()
distinct()
sorted()
peek()
limit()
skip(

We will see example programs on each operation in the further article.

2. filter() 

Returns a stream consisting of the elements of this stream that
match the given predicate.

Syntax:

1
Stream filter​(Predicate predicate)

Example:

1
2
3
4
Stream intStream = Stream.of(1, 2, 3, 4, 5);
Stream subStream = intStream.filter(value -> value > 3);
long count = subStream.count();
System.out.println(count);

Output:

1
2

This program takes Predicate functional interface as lambda and checks for the number is greater than 3.

3. map()

Returns a stream consisting of
the results of applying the given function to the elements of this stream.

Syntax: 

1
Stream map​(Function mapper)

Example:

1
2
3
4
5
6
7
8
9
// map() Operation
Stream strStream = Stream.of("Welcome", "To", "java", "blog");
Stream subStream2 = strStream.map(string -> {
 if (string == "java")
  return "Java-W3schools";
 return string;
});
List welomeList = subStream2.collect(Collectors.toList());
System.out.println(welomeList);

Here, map function takes an argument type of Function. The function is a functional interface and has a method
apply(). This method takes a value and returns another value.

Output:

1
[Welcome, To, Java-W3schools, blog]

In this example, replacing the word “java” with “Java-W3schools”.

map() wrpper types are also comes under intermediate operations category.

mapToDouble(), mapToLong(), mapToInt()

4. flatMap()

This flatmap works best for a list of collections. We will show the example with two lists and how to convert them into a single stream using
flatmap() method.

syntax:

1
Stream flatMap​(Function> mapper)

Example:

Example program to count the number of unique fruit names from two lists.

1
2
3
4
Stream flatStream = stream.flatMap(list -> list.stream());
//flatStream.forEach(str -> System.out.println(str));
long distinctFruites = flatStream.distinct().count();
System.out.println(distinctFruites);

Output:

1
6

And also see the most common problem with solution when working with Stream “stream has already been operated upon or closed“. After uncomming line flatStream.forEach(str -> System.out.println(str)); this program will exception java.lang.IllegalStateException.

Similar flatMap() methods for wrapper types such as flatMapToInt(), flatMapToLong(), flatMapToDouble().

5. distinct()

Returns a stream consisting of the distinct elements (according to Object.equals(Object)) of this stream.

For ordered streams, the selection of distinct elements is stable (for duplicated elements, the element appearing first in the encounter order is preserved.) For unordered streams, no stability guarantees are made.

Syntax:

1
Stream distinct()

Example:

1
2
3
4
// distinct() Operation
Stream fruitsStream = Stream.of("Apple", "Jack Fruit", "Water Melon", "Apple");
Stream distinctStream = fruitsStream.distinct();
distinctStream.forEach(name -> System.out.println(name));

Output:

1
2
3
Apple
Jack Fruit
Water Melon

6. sorted()

Returns a stream consisting of the elements of this stream, sorted according to the natural order.

If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.


Note: For ordered streams, the sort is stable. For unordered streams, no stability guarantees are made.

Syntax:

1
Stream sorted()

Example:

1
2
3
4
// sort() Operation
Stream vegStream = Stream.of("tomoto", "Green Chilli", "Pototo", "Beet root");
Stream sortedStream = vegStream.sorted();
sortedStream.forEach(name -> System.out.println(name));

Output:

1
2
3
4
Beet root
Green Chilli
Pototo
tomoto

7. peek()

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.

peek() method is the best way to debug the streams in Java 8. The eclipse will not support for debugging.

Note: We can not predict the order of peek() invocation for parallel stream pipelines.

Syntax:

1
Stream peek​(Consumer action)

Example:

1
2
3
4
// peek() Operation
Stream.of("one", "two", "three", "four").filter(e -> e.length() > 3)
  .peek(e -> System.out.println("Filtered value: " + e)).map(String::toUpperCase)
  .peek(e -> System.out.println("Mapped value: " + e)).collect(Collectors.toList());

For each time filter condition satisfies, immediately peek() method will be invoked. See the output, you’ll understand better.

Output:

1
2
3
4
Filtered value: three
Mapped value: THREE
Filtered value: four
Mapped value: FOUR

8. limit()

Returns a stream with the limited size given. It will truncate the remaining elements from the stream.


Note: limit() is suitable for sequential streams and cannot give good performance results for parallel streams.

Syntax:

1
Stream limit​(long maxSize)

Example:

Program to limit the stream to first two elements.

1
Stream.of("one", "two", "three", "four").limit(2).forEach(item -> System.out.println(item));

Output:

1
2
one
two

9. skip()

This method skips the given n elements and returns a Stream. This is the most useful when want to perform any operations on last n records or lines from a List or Stream.

Syntax:

1
Stream skip​(long n)

Example:

program to skip the first 2 elements and print remaining elements.

1
Stream.of("one", "two", "three", "four", "five").skip(2).forEach(item -> System.out.println(item));

Output:

1
2
3
three
four
five

10. Conclusion

In this tutorial, We’ve seen what is Intermediate Operation in Streams. How intermediate operations work in new Java 8 Streams.

And also discussed a list of all intermediate methods with example programs.

All the programs shown in this post are over GitHub.

Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Java 8 Stream Intermediate Operations (Methods) Examples

Opinions expressed by Java Code Geeks contributors are their own.

Venkatesh Nukala

Venkatesh Nukala is a Software Engineer working for Online Payments Industry Leading company. In my free time, I would love to spend time with family and write articles on technical blogs. More on JavaProgramTo.com
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
4 years ago

Hi, the flatMap example is uncomplete :
1- the syntax is not correct : Stream flatMap​(Function> mapper)
2- Where are the two lists of fruits ?
3- this commented line of code is useless : //flatStream.forEach(str -> System.out.println(str));

Regards.

Back to top button