Java Stream map()与实例
Stream map(Function mapper) 返回一个由对该流的元素应用给定函数的结果组成的流。
Stream map(Function mapper)是一个 中间操作 这些操作始终是懒惰的。中间操作是在一个流实例上调用的,在它们完成处理后,会给出一个流实例作为输出:
语法:
<R> Stream<R> map(Function<? super T, ? extends R> mapper)
其中,R是新流的元素类型。流是一个接口,T是流元素的类型。流元素的类型。Mapper是一个无状态函数 它被应用于每个元素,该函数 返回新的流。
例1: 流映射()函数,对流中的每个元素进行数字*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<Integer> 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<String> 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<String> 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<String> 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