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
相關用法
- Java Stream map()用法及代碼示例
- Java Stream filter()用法及代碼示例
- Java Stream findAny()用法及代碼示例
- Java Stream anyMatch()用法及代碼示例
- Java Stream mapToLong()用法及代碼示例
- Java Stream allMatch()用法及代碼示例
- Java Stream.reduce()用法及代碼示例
- Java Stream min()用法及代碼示例
- Java Stream.max()用法及代碼示例
- Java Stream toArray()用法及代碼示例
- Java Stream empty()用法及代碼示例
- Java Stream findFirst()用法及代碼示例
- Java Stream flatMap()用法及代碼示例
- Java Stream flatMapToDouble()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream flatMapToInt() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。