Java中的 Stream map() 示例
流映射(函数映射器)返回一个流,该流由将给定函数应用于该流的元素的结果组成。
Stream map(函数 mapper)是一个中间操作。这些操作总是懒惰的。在 Stream 实例上调用中间操作,在它们完成处理后,它们给出一个 Stream 实例作为输出。
句法 :
Stream 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.
示例 1: Stream map()函数,对流的每个元素进行数字 * 3 的操作。
// Java code for Stream map(Function mapper)
// to get a stream by applying the
// given function to this stream.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
System.out.println("The stream after applying "
+ "the function is : ");
// Creating a list of Integers
List list = Arrays.asList(3, 6, 9, 12, 15);
// Using Stream map(Function mapper) and
// displaying the corresponding new stream
list.stream().map(number -> number * 3).forEach(System.out::println);
}
}
输出 :
The stream after applying the function is :
9
18
27
36
45
示例 2: Stream map()函数,具有将小写转换为大写的操作。
// Java code for Stream map(Function mapper)
// to get a stream by applying the
// given function to this stream.
import java.util.*;
import java.util.stream.Collectors;
class GFG {
// Driver code
public static void main(String[] args)
{
System.out.println("The stream after applying "
+ "the function is : ");
// Creating a list of Integers
List list = Arrays.asList("geeks", "gfg", "g",
"e", "e", "k", "s");
// Using Stream map(Function mapper) to
// convert the Strings in stream to
// UpperCase form
List answer = list.stream().map(String::toUpperCase).
collect(Collectors.toList());
// displaying the new stream of UpperCase Strings
System.out.println(answer);
}
}
输出 :
The stream after applying the function is :
[GEEKS, GFG, G, E, E, K, S]
示例 3: Stream map()函数,使用映射字符串长度代替字符串的操作。
// Java code for Stream map(Function mapper)
// to get a stream by applying the
// given function to this stream.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
System.out.println("The stream after applying "
+ "the function is : ");
// Creating a list of Strings
List list = Arrays.asList("Geeks", "FOR", "GEEKSQUIZ",
"Computer", "Science", "gfg");
// Using Stream map(Function mapper) and
// displaying the length of each String
list.stream().map(str -> str.length()).forEach(System.out::println);
}
}
输出 :
The stream after applying the function is :
5
3
9
8
7
3