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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。