当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Stream flatMapToInt()用法及代码示例


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

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

IntStream flatMapToInt(Function<? super T, ? extends IntStream> 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()函数,具有将字符串解析为Integer的操作。


// 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); 
    } 
}

输出:

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

输出:

5
3
13
3


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream flatMapToInt() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。