如果流具有已定义的遇到顺序,则流forEachOrdered(Consumer action)将对该流的每个元素执行操作,并按流的遇到顺序进行。 Stream forEachOrdered(Consumer action)是一项终端操作,即,它可以遍历该流以产生结果或副作用。
用法:
void forEachOrdered(Consumer<? super T> action) Where, Consumer is a functional interface which is expected to operate via side-effects. and T is the type of stream elements.
注意:此操作一次处理一个元素,如果存在则按遭遇顺序。对一个元素执行操作happens-before对后续元素执行操作。
示例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<Integer> 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<String> 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<String> 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
相关用法
- Java LongStream forEachOrdered()用法及代码示例
- Java IntStream forEachOrdered()用法及代码示例
- Java DoubleStream forEachOrdered()用法及代码示例
- Java Stream min()用法及代码示例
- Java Stream.max()用法及代码示例
- Java Stream count()用法及代码示例
- Java OptionalInt stream()用法及代码示例
- Java OptionalLong stream()用法及代码示例
- Java Stream generate()用法及代码示例
- Java OptionalDouble stream()用法及代码示例
- Java BitSet stream()用法及代码示例
- Java Stream ofNullable(T)用法及代码示例
- Java Optional stream()用法及代码示例
- Java Stream dropWhile()用法及代码示例
- Java Stream takeWhile()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Stream forEachOrdered() method in Java with examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。