Stream mapToInt(ToIntFunction mapper)返回一个IntStream,其中包括将给定函数应用于此流的元素的结果。
流mapToInt(ToIntFunction mapper)是一个中间操作。这些操作总是很懒。在Stream实例上调用中间操作,并在完成处理后将中间实例作为输出提供。
用法:
IntStream mapToInt(ToIntFunction<? super T> mapper) Where, IntStream is a sequence of primitive int-valued elements 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:mapToInt()具有将流元素除以3的函数。
// Java code for Stream mapToInt
// (ToIntFunction mapper) to get a
// IntStream by applying the given function
// to the elements of this stream.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of Strings
List<String> list = Arrays.asList("3", "6", "8",
"14", "15");
// Using Stream mapToInt(ToIntFunction mapper)
// and displaying the corresponding IntStream
list.stream().mapToInt(num -> Integer.parseInt(num))
.filter(num -> num % 3 == 0)
.forEach(System.out::println);
}
}
输出:
3 6 15
示例2:mapToInt()在执行具有其长度的映射字符串的操作后返回IntStream。
// Java code for Stream mapToInt
// (ToIntFunction mapper) to get a
// IntStream by applying the given function
// to the elements of this stream.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of Strings
List<String> list = Arrays.asList("Geeks", "for", "gfg",
"GeeksforGeeks", "GeeksQuiz");
// Using Stream mapToInt(ToIntFunction mapper)
// and displaying the corresponding IntStream
// which contains length of each element in
// given Stream
list.stream().mapToInt(str -> str.length()).forEach(System.out::println);
}
}
输出:
5 3 3 13 9
相关用法
- Java LongStream mapToInt()用法及代码示例
- Java DoubleStream mapToInt()用法及代码示例
- Java Stream map()用法及代码示例
- Java Stream filter()用法及代码示例
- Java Stream mapToLong()用法及代码示例
- Java Stream anyMatch()用法及代码示例
- Java Stream allMatch()用法及代码示例
- Java Stream peek()用法及代码示例
- Java Stream mapToDouble()用法及代码示例
- Java Stream flatMap()用法及代码示例
- Java Stream findFirst()用法及代码示例
- Java Stream toArray()用法及代码示例
- Java Stream flatMapToDouble()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream mapToInt() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。