Stream mapToLong(ToLongFunction mapper)返回一個LongStream,其中包括將給定函數應用於此流的元素的結果。
流mapToLong(ToLongFunction mapper)是一個中間操作。這些操作總是很懶。在Stream實例上調用中間操作,並在完成處理後將中間實例作為輸出提供。
用法:
LongStream mapToLong(ToLongFunction<? super T> mapper) Where, LongStream is a sequence of primitive long-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:mapToLong()函數,具有返回滿足給定函數的流的操作。
// Java code for Stream mapToLong
// (ToLongFunction mapper) to get a
// LongStream by applying the given function
// to the elements of this stream.
import java.util.*;
class GFG {
// Driver code
public static void main(String[] args)
{
System.out.println("The stream after applying "
+ "the function is:");
// Creating a list of Strings
List<String> list = Arrays.asList("25", "225", "1000",
"20", "15");
// Using Stream mapToLong(ToLongFunction mapper)
// and displaying the corresponding LongStream
list.stream().mapToLong(num -> Long.parseLong(num))
.filter(num -> Math.sqrt(num) / 5 == 3 )
.forEach(System.out::println);
}
}
輸出:
The stream after applying the function is: 225
範例2:mapToLong()函數,以字符串長度返回set-bits。
// Java code for Stream mapToLong
// (ToLongFunction mapper) to get a
// LongStream 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("Data Structures", "JAVA", "OOPS",
"GeeksforGeeks", "Algorithms");
// Using Stream mapToLong(ToLongFunction mapper)
// and displaying the corresponding LongStream
// which contains the number of one-bits in
// binary representation of String length
list.stream().mapToLong(str -> Long.bitCount(str.length()))
.forEach(System.out::println);
}
}
輸出:
4 1 1 3 2
相關用法
- Java DoubleStream mapToLong()用法及代碼示例
- Java IntStream mapToLong()用法及代碼示例
- Java Stream map()用法及代碼示例
- Java Stream flatMapToLong()用法及代碼示例
- Java Stream flatMapToInt()用法及代碼示例
- Java Stream min()用法及代碼示例
- Java Stream mapToInt()用法及代碼示例
- Java Stream builder()用法及代碼示例
- Java Stream empty()用法及代碼示例
- Java Stream peek()用法及代碼示例
- Java Stream.max()用法及代碼示例
- Java Stream.reduce()用法及代碼示例
- Java Stream mapToDouble()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Stream mapToLong() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。