流映射(函数映射器)返回一个流,该流包含将给定函数应用于此流的元素的结果。
流映射(函数映射器)是一个中间操作。这些操作总是很懒。在Stream实例上调用中间操作,并在完成处理后将中间实例作为输出提供。
用法:
<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.
示例1:流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<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:流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:流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
相关用法
- Java Stream peek()用法及代码示例
- Java Stream min()用法及代码示例
- Java Stream.max()用法及代码示例
- Java Stream mapToInt()用法及代码示例
- Java Stream flatMapToInt()用法及代码示例
- Java Stream flatMapToLong()用法及代码示例
- Java Stream flatMapToDouble()用法及代码示例
- Java Stream flatMap()用法及代码示例
- Java Stream findFirst()用法及代码示例
- Java Stream findAny()用法及代码示例
- Java Stream builder()用法及代码示例
- Java Stream empty()用法及代码示例
- Java Stream toArray()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream map() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。