Friday, April 10, 2020

Streams API in Java 8 – Intermediate Operations

In this blog, lets learn to perform intermediate operations in Streams.You can understand about streams and learn to create streams in Part-I of the Streams API in Java 8 series. Now, let us learn the intermediate operations with examples.
filter()
sorted()
map()
limit()
flatMap()
concat()

filter()
filter() is an intermediate operation. The syntax is filter(Predicate predicate).It takes Predicate as parameter. You can use lambda or method references to implement Predicate.
The result of filter is a stream. so, a terminal operation is needed to get the result back. To start with we will use forEach() to get the result.
forEach() is an intermediate operation which takes Consumer as parameter.Let us use method references inside forEach() method.
Example:
Code snippet for filter() methodJava
List<String> list = Arrays.asList("Java","Maven","CSS","JUnit","HTML","JSP");
// convert list into stream
// filter the list based on the condition
// call forEach that is a terminal operation
list.stream()
.filter((str)->str.length()>3)
.forEach(System.out::println);
Output:
Java
Maven
JUnit
HTML

sorted()
sorted() is an intermediate operation. It returns a stream consisting of the elements, sorted according to natural order. It has one overloaded method that takes Comparator as parameter. The syntax is sort(Comparator compare).You can use lambda or method references to implement Comparator.
This can be used in case of a collection of objects. Here also we will use forEach() for terminal operation. I am using method chaining by adding methods
Example:
Code snippet for sorted() methodJava
// convert list into stream
// filter the list based on a condition
// call sorted on the stream
// call forEach that is a terminal operation
Arrays.asList("Java","Maven","CSS","JUnit","HTML","JSP")
.stream()
.filter((str)->str.length()>3)
.sorted()
.forEach(System.out::println);
Output:
HTML
JUnit
Java
Maven

map()
map() is an intermediate operation. It returns a stream that is a result of applying a function to all the elements in the stream.The syntax is map(Function mapper).You can use lambda or method references to implement Function. So it can be either map(String::toUpperCase) or map(str->str.toUpperCase()).
In case of String Stream pass the method of String inside map, in case of Integer Stream , pass the functionality of Integer inside map.
Here also we will use forEach() for terminal operation.
Example:
Code snippet for map() methodJava
// convert list into stream
// filter the list based on a condition
// call sorted on the stream
// convert each element to uppercase - uses method reference
// call forEach that is a terminal operation
Arrays.asList("Java","Maven","CSS","JUnit","HTML","JSP")
.stream()
.filter((str)->str.length()>3)
.sorted()
.map(String::toUpperCase)
.forEach(System.out::println);
// For integer Stream
Stream.of(new Integer[] {10,20,40})
.map(num->num.doubleValue())
.forEach(System.out::println);
Output:
10.0
20.0
40.0

limit()
limit() is an intermediate operation. It returns a stream that limits the size of the stream to the given length.The syntax is limit(int length). It throws IllegalArgumentException in case of negative length.
Here also we will use forEach() for terminal operation.
Example:
Code snippet for limit() methodJava
Arrays.asList("Java","Maven","CSS","JUnit","HTML","JSP")
.stream()
.filter((str)->str.length()>3)
.sorted()
.map(String::toUpperCase)
.limit(3)
.forEach(System.out::println);
output:
HTML
JAVA
JUNIT

skip()
skip() is an intermediate operation. It returns a stream after discarding the first n elements of the stream.If the stream has less elements than n, then an empty stream will be returned.The syntax is skip(int length).
Here also we will use forEach() for terminal operation.
Example:
code snippet for skip() methodJava
Arrays.asList("Java","Maven","CSS","JUnit","HTML","JSP")
.stream()
.map(x->x.toUpperCase())
.sorted()
.skip(2)
.forEach(System.out::println);
output:
JAVA
JSP
JUNIT
MAVEN

flatMap()
flatMap() is an intermediate operation. Flatmap is used when the stream itself is of type List, Set or an Array, that is Stream<List<String>>or Stream<Set<String>> or Stream<String[]> or Stream<List<Object>>.
It is used to convert a Stream of Collection or array into a Stream of single elements of that particular datatype. It returns a stream after applying the provided mapping function to each element. The syntax is flatMap(Function mapper).
using flatMap() methodJava
Stream<String[]>      -> flatMap -> Stream<String>
Stream<Set<String>>   -> flatMap -> Stream<String>
Stream<List<String>>  -> flatMap -> Stream<String>
Stream<List<Object>>  -> flatMap ->     Stream<Object>
Stream<String[]>      -> flatMap -> Stream<String>
Stream<Set<String>>   -> flatMap -> Stream<String>
Stream<List<String>>  -> flatMap -> Stream<String>
Stream<List<Object>>  -> flatMap ->     Stream<Object>
Example:
code snippet for flatMap() methodJava
String[][] arrTwo = new String[][]
{ { "Rama", "Janani","Rohan" },
{ "Akash", "Rahul", "Kumaran" } };
//converting a TwoD array to stream of oneDimensional array
Stream<String[]> onestream = Arrays.stream(arrTwo);
//stream of oneDimensional array to Stream of String elements
Stream<String> strStream =
onestream.flatMap((row)->Arrays.stream(row))
.filter((x)->x.startsWith("R"));
strStream.forEach(System.out::println);
// As method chaining
String[][] arrTwo = new String[][]
{ { "Rama", "Janani","Rohan" },{ "Akash", "Rahul", "Kumaran" } };
Arrays.stream(arrTwo)
.flatMap((row)->Arrays.stream(row))
.filter((x)->x.startsWith("R"))
.forEach(System.out::println);
output:
Rama
Rohan
Rahul
                String[][] arrTwo = new String[][]
 { { "Rama", "Janani","Rohan" },
   { "Akash", "Rahul", "Kumaran" } };
 //converting a TwoD array to stream of oneDimensional array
 Stream<String[]> onestream = Arrays.stream(arrTwo);
 //stream of oneDimensional array to Stream of String elements
 Stream<String> strStream =
 onestream.flatMap((row)->Arrays.stream(row))
 .filter((x)->x.startsWith("R"));
 strStream.forEach(System.out::println);
// As method chaining
String[][] arrTwo = new String[][]
 { { "Rama", "Janani","Rohan" },{ "Akash", "Rahul", "Kumaran" } };
Arrays.stream(arrTwo)
      .flatMap((row)->Arrays.stream(row))
      .filter((x)->x.startsWith("R"))
      .forEach(System.out::println);
Output:
Rama
Rohan
Rahul

concat()
concat() is an intermediate operation. It returns a concatenated stream with all the elements of the first stream followed by all the elements of the second stream. The syntax is stream(Stream a, Stream b).
Here also we will use forEach() for terminal operation.
Example:
Code snippet for concat() methodJava
Stream.concat(Stream.of("Apple","Orange"),Stream.of("Kiwi","Papaya"))
.forEach(System.out::println);
output:
Apple
Orange
Kiwi
Papaya

No comments:

Post a Comment

Your Quantum Reality

Your reality is created from within yourself. Everything you see on the outside in your life is a reflection of your thoughts, beliefs an...