$show=/label

Java 8 Stream Intermediate Operations (Methods) Examples

SHARE:

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.

Java 8 Stream Intermediate Operations (Methods)

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.

Stream Intermediate Operations:

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:

Stream filter​(Predicate predicate)

Example:

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:

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: 


 Stream map​(Function mapper)


Example:


// 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:

[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:

<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)

Example:


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

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

Output:


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:

Stream distinct()

Example:


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

Output:


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:

Stream sorted()

Example:


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

Output:

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:

Stream peek​(Consumer action)

Example:


// 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:

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:

Stream limit​(long maxSize)

Example:

Program to limit the stream to first two elements.

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

Output:

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:

Stream skip​(long n)

Example:

program to skip the first 2 elements and print remaining elements.
Stream.of("one", "two", "three", "four", "five").skip(2).forEach(item -> System.out.println(item));

Output:


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.

Intermediate Operations API

List of Stream Operations

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Java 8 Stream Intermediate Operations (Methods) Examples
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.
https://1.bp.blogspot.com/-BE4tTemCdIQ/XRTTbnZvhvI/AAAAAAAABsM/QlrXF54pBXIWAUOBJPFnGp0htCRHBwnYwCLcBGAs/s320/Java%2B8%2BStream%2BIntermediate%2BOperations%2B%2528Methods%2529.png
https://1.bp.blogspot.com/-BE4tTemCdIQ/XRTTbnZvhvI/AAAAAAAABsM/QlrXF54pBXIWAUOBJPFnGp0htCRHBwnYwCLcBGAs/s72-c/Java%2B8%2BStream%2BIntermediate%2BOperations%2B%2528Methods%2529.png
JavaProgramTo.com
https://www.javaprogramto.com/2019/06/java-8-stream-intermediate-operations.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2019/06/java-8-stream-intermediate-operations.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content