📜  使用示例在Java中流式传输 flatMapToInt()

📅  最后修改于: 2022-05-13 01:55:27.287000             🧑  作者: Mango

使用示例在Java中流式传输 flatMapToInt()

Stream flatMapToInt(函数 mapper)返回一个 IntStream ,其中包含将此流的每个元素替换为通过将提供的映射函数应用于每个元素而生成的映射流的内容的结果。 Stream flatMapToInt(函数 mapper) 是一个中间操作。这些操作总是懒惰的。在 Stream 实例上调用中间操作,在它们完成处理后,它们给出一个 Stream 实例作为输出。

注意:每个映射的流在其内容放入此流后关闭。如果映射流为空,则使用空流。
句法 :

IntStream flatMapToInt(Function 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: 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 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);
    }
}

输出 :

1
2
3
4
5

示例 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 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);
    }
}

输出 :

5
3
13
3