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:
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:
Streamfilter(Predicate predicate)
Example:
StreamintStream = 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 StreamstrStream = 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.
StreamflatStream = 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:
Streamdistinct()
Example:
// distinct() Operation StreamfruitsStream = 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:
Streamsorted()
Example:
// sort() Operation StreamvegStream = 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:
Streampeek(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:
Streamlimit(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:
Streamskip(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
No comments:
Post a Comment
Please do not add any spam links in the comments section.