Java Stream flatMapToInt()与实例
Stream flatMapToInt(Function mapper) 返回一个IntStream,它由将此流中的每个元素替换为对每个元素应用所提供的映射函数而产生的映射流内容的结果组成。Stream flatMapToInt(Function mapper)是一个 中间操作 这些操作始终是懒惰的。中间操作在一个Stream实例上被调用,在它们完成处理后,会给出一个Stream实例作为输出:
注意: 每个映射的流在其内容被放入该流后被关闭。如果一个映射的流是空的,则使用一个空的流来代替。
语法
IntStream flatMapToInt(Function <? super T, ? extends IntStream> mapper)
其中,IntStream是一串原始的 int-value元素的序列,T是流元素的类型。流元素的类型。映射器是一个无状态函数 它被应用于每个元素,并且该函数 返回新的流。
例1: flatMapToInt()函数的操作是将字符串解析为整数。
// Java code for Stream flatMapToInt// (Function mapper) to get an IntStream// consisting of the results of replacing// each element of this stream with the// contents of a mapped stream.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating a list of Strings List<String> list = Arrays.asList("1", "2", "3", "4", "5"); // Using Stream flatMapToInt(Function mapper) list.stream().flatMapToInt(num -> IntStream.of(Integer.parseInt(num))). forEach(System.out::println); }}
输出:
12345
例2: flatMapToInt()函数的操作是将字符串与它们的长度进行映射。
// Java code for Stream flatMapToInt// (Function mapper) to get an IntStream// consisting of the results of replacing// each element of this stream with the// contents of a mapped stream.import java.util.*;import java.util.stream.IntStream; class GFG { // Driver code public static void main(String[] args) { // Creating a List of Strings List<String> list = Arrays.asList("Geeks", "GFG", "GeeksforGeeks", "gfg"); // Using Stream flatMapToInt(Function mapper) // to get length of all strings present in list list.stream().flatMapToInt(str -> IntStream.of(str.length())). forEach(System.out::println); }}输出:
53133
