Stream map() in Java with examples
Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream.
Stream map(Function mapper) is an intermediate operation. These operations are always lazy. Intermediate operations are invoked on a Stream instance and after they finish their processing, they give a Stream instance as output.
Syntax :
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
where, R is the element type of the new stream.
Stream is an interface and T is the type
of stream elements. mapper is a stateless function
which is applied to each element and the function
returns the new stream.
Example 1 : Stream map() function with operation of number * 3 on each element of stream.
import java.util.*;
class GFG {
public static void main(String[] args)
{
System.out.println( "The stream after applying "
+ "the function is : " );
List<Integer> list = Arrays.asList( 3 , 6 , 9 , 12 , 15 );
list.stream().map(number -> number * 3 ).forEach(System.out::println);
}
}
|
Output :
The stream after applying the function is :
9
18
27
36
45
Example 2 : Stream map() function with operation of converting lowercase to uppercase.
import java.util.*;
import java.util.stream.Collectors;
class GFG {
public static void main(String[] args)
{
System.out.println( "The stream after applying "
+ "the function is : " );
List<String> list = Arrays.asList( "geeks" , "gfg" , "g" ,
"e" , "e" , "k" , "s" );
List<String> answer = list.stream().map(String::toUpperCase).
collect(Collectors.toList());
System.out.println(answer);
}
}
|
Output :
The stream after applying the function is :
[GEEKS, GFG, G, E, E, K, S]
Example 3 : Stream map() function with operation of mapping string length in place of string.
import java.util.*;
class GFG {
public static void main(String[] args)
{
System.out.println( "The stream after applying "
+ "the function is : " );
List<String> list = Arrays.asList( "Geeks" , "FOR" , "GEEKSQUIZ" ,
"Computer" , "Science" , "gfg" );
list.stream().map(str -> str.length()).forEach(System.out::println);
}
}
|
Output :
The stream after applying the function is :
5
3
9
8
7
3
Last Updated :
06 Dec, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...