當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Stream mapToInt()用法及代碼示例


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


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream mapToInt() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。