當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java LongStream peek()用法及代碼示例


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


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 LongStream peek() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。