Java IntStream peek()方法及示例

Java IntStream peek()方法及示例

IntStream peek()java.util.stream.IntStream的一个方法。该函数返回一个由该流的元素组成的流,当元素从产生的流中被消耗时,另外对每个元素执行所提供的操作。

语法:

IntStream peek(IntConsumer action)

其中,IntStream是一串原始的
元素的序列,该函数返回
一个并行的IntStream,IntConsumer表示
一个接受单一int值参数的操作。

例1: 对一个给定范围的流进行求和。

// Java code for IntStream peek()
// where the action performed is to get
// sum of all elements in given range
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
      
    // Creating a stream of integers
    IntStream stream = IntStream.range(2, 10);
      
    // performing action sum on elements of 
    // given range and storing the result in sum
    int 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 IntStream peek()
// where the action performed is to get
// count of all elements in given range
import java.util.*;
import java.util.stream.IntStream;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
      
    // Creating a stream of integers
    IntStream stream = IntStream.range(2, 10);
      
    // 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 IntStream 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.IntStream;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
      
    // Creating a stream of integers
    IntStream stream = IntStream.range(2, 10);
  
    // 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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程