📜  在Java中流式传输 forEachOrdered() 方法及示例

📅  最后修改于: 2022-05-13 01:54:47.796000             🧑  作者: Mango

在Java中流式传输 forEachOrdered() 方法及示例

Stream forEachOrdered(Consumer action)对该流的每个元素执行一个操作,如果流具有定义的遇到顺序,则按照流的遇到顺序。 Stream forEachOrdered(Consumer action) 是一个终端操作,即它可以遍历流以产生结果或副作用。

句法 :

void forEachOrdered(Consumer action)

Where, Consumer is a functional interface which 
is expected to operate via side-effects. and T 
is the type of stream elements.

注意:此操作一次处理一个元素,如果存在则按遇到的顺序。对一个元素执行操作发生在对后续元素执行操作之前。

示例 1:以原始顺序打印整数数组的元素。

// Java code for forEachOrdered
// (Consumer action) in Java 8
import java.util.*;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
  
    // Creating a list of Integers
    List list = Arrays.asList(10, 19, 20, 1, 2);
      
    // Using forEachOrdered(Consumer action) to 
    // print the elements of stream in encounter order
    list.stream().forEachOrdered(System.out::println);
      
  
}
}
输出:
10
19
20
1
2

示例 2:以原始顺序打印字符串数组的元素。

// Java code for forEachOrdered
// (Consumer action) in Java 8
import java.util.*;
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
  
    // Creating a list of Strings
    List list = Arrays.asList("GFG", "Geeks", 
                             "for", "GeeksforGeeks");
      
    // Using forEachOrdered(Consumer action) to 
    // print the elements of stream in encounter order
    list.stream().forEachOrdered(System.out::println);
      
  
}
}
输出:
GFG
Geeks
for
GeeksforGeeks

示例 3:以原始顺序打印字符数组索引 2 处的字符串。

// Java code for forEachOrdered
// (Consumer action) in Java 8
import java.util.*;
import java.util.stream.Stream;
  
  
class GFG {
      
    // Driver code
    public static void main(String[] args) {
  
    // Creating a Stream of Strings
    Stream stream = Stream.of("GFG", "Geeks", 
                             "for", "GeeksforGeeks");
      
    // Using forEachOrdered(Consumer action) 
    stream.flatMap(str-> Stream.of(str.charAt(2)))
          .forEachOrdered(System.out::println);
      
  
}
}
输出:
G
e
r
e