Stream flatMapToDouble(Function mapper)返回一個DoubleStream,該DoubleStream包含將該流的每個元素替換為通過將提供的映射函數應用於每個元素而生成的映射流的內容而得到的結果。 Stream flatMapToDouble(Function mapper)是一個中間操作。這些操作總是很懶。在Stream實例上調用中間操作,並在完成處理後將中間實例作為輸出提供。
注意:將每個映射流的內容放入該流後,將其關閉。如果映射的流為null,則使用空流。
用法:
DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper) Where, DoubleStream is a sequence of primitive double-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:flatMapToDouble()函數,具有將字符串解析為兩倍的操作。
// Java code for Stream flatMapToDouble
// (Function mapper) to get an DoubleStream
// 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.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a list of Strings
List<String> list = Arrays.asList("1.5", "2.7", "3",
"4", "5.6");
// Using Stream flatMapToDouble(Function mapper)
list.stream().flatMapToDouble(num
-> DoubleStream.of(Double.parseDouble(num)))
.forEach(System.out::println);
}
}
輸出:
1.5 2.7 3.0 4.0 5.6
示例2:flatMapToDouble()函數,用於返回具有字符串長度的流。
// Java code for Stream flatMapToDouble
// (Function mapper) to get an DoubleStream
// 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.DoubleStream;
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 flatMapToDouble(Function mapper)
// to get length of all strings present in list
list.stream().flatMapToDouble(str
-> DoubleStream.of(str.length()))
.forEach(System.out::println);
}
}
輸出:
5.0 3.0 13.0 3.0
相關用法
- Java Stream map()用法及代碼示例
- Java Stream peek()用法及代碼示例
- Java Stream min()用法及代碼示例
- Java Stream.max()用法及代碼示例
- Java Stream flatMapToInt()用法及代碼示例
- Java Stream findAny()用法及代碼示例
- Java Stream filter()用法及代碼示例
- Java Stream anyMatch()用法及代碼示例
- Java Stream.reduce()用法及代碼示例
- Java Stream allMatch()用法及代碼示例
- Java Stream flatMapToLong()用法及代碼示例
- Java Stream findFirst()用法及代碼示例
- Java Stream toArray()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream flatMapToDouble() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。