📜  Java中的流式 mapToInt() 和示例

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

Java中的流式 mapToInt() 和示例

Stream mapToInt(ToIntFunction mapper)返回一个 IntStream,其中包含将给定函数应用于此流的元素的结果。

Stream mapToInt(ToIntFunction mapper) 是一个中间操作。这些操作总是懒惰的。在 Stream 实例上调用中间操作,在它们完成处理后,它们给出一个 Stream 实例作为输出。

句法 :

IntStream mapToInt(ToIntFunction 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 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 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