LongStream peek()是java.util.stream.LongStream中的方法。该函数返回由该流的元素组成的流,并在从结果流中消耗元素时对每个元素另外执行提供的操作。
用法:
LongStream peek(LongConsumer action) Where, LongStream is a sequence of primitive long-valued elements and the function returns a parallel LongStream and LongConsumer represents an operation that accepts a single long-valued argument.
示例1:在给定范围的流上执行求和。
// Java code for LongStream peek()
// where the action performed is to get
// sum of all elements in given range
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a stream of longs
LongStream stream = LongStream.range(2L, 10L);
// performing action sum on elements of
// given range and storing the result in sum
long sum = stream.peek(System.out::println).sum();
// Displaying the result of action performed
System.out.println("sum is : " + sum);
}
}
输出:
2 3 4 5 6 7 8 9 sum is : 44
示例2:在给定范围的流上执行计数操作。
// Java code for LongStream peek()
// where the action performed is to get
// count of all elements in given range
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a stream of longs
LongStream stream = LongStream.range(2L, 10L);
// performing action count on elements of
// given range and storing the result in Count
long Count = stream.peek(System.out::println).count();
// Displaying the result of action performed
System.out.println("count : " + Count);
}
}
输出:
2 3 4 5 6 7 8 9 count : 8
示例3:在给定范围的流上执行平均操作。
// Java code for LongStream peek()
// where the action performed is to get
// average of all elements in given range
import java.util.*;
import java.util.OptionalDouble;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// Creating a stream of longs
LongStream stream = LongStream.range(2L, 10L);
// performing action average on elements of
// given range and storing the result in avg
OptionalDouble avg = stream.peek(System.out::println)
.average();
// If a value is present, isPresent()
// will return true, else -1 is displayed.
if (avg.isPresent()) {
System.out.println("Average is : " + avg.getAsDouble());
}
else {
System.out.println("-1");
}
}
}
输出:
2 3 4 5 6 7 8 9 Average is : 5.5
相关用法
- Java Stream peek()用法及代码示例
- Java DoubleStream peek()用法及代码示例
- Java IntStream peek()用法及代码示例
- Java LongStream max()用法及代码示例
- Java LongStream min()用法及代码示例
- Java BlockingDeque peek()用法及代码示例
- Java LongStream empty()用法及代码示例
- Java LongStream count()用法及代码示例
- Java LongStream filter()用法及代码示例
- Java LongStream anyMatch()用法及代码示例
- Java LongStream mapToInt()用法及代码示例
- Java LongStream noneMatch()用法及代码示例
- Java LongStream distinct()用法及代码示例
- Java LongStream average()用法及代码示例
- Java LongStream allMatch()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 LongStream peek() in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。