如果流具有已定義的遇到順序,則流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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。