Java Stream mapToLong()示例
Stream mapToLong(ToLongFunction mapper) 返回一个LongStream,它由对这个流的元素应用给定函数的结果组成。
Stream mapToLong(ToLongFunction mapper)是一个 中间操作。 这些操作始终是懒惰的。中间操作是在一个Stream实例上调用的,在它们完成处理后,会给出一个Stream实例作为输出:
语法:
LongStream mapToLong(ToLongFunction < ? super T > mapper)
其中,LongStream是一串原始的 长值元素的序列,T是流元素的类型。流元素的类型。Mapper是一个无状态函数 它被应用于每个元素,该函数 返回新的流。
例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()函数,返回字符串长度中的设定位数。
// 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