Stream forEachOrdered(Consumer action) performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. Stream forEachOrdered(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.
Syntax :
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.
Note : This operation processes the elements one at a time, in encounter order if one exists. Performing the action for one element happens-before performing the action for subsequent elements.
Example 1 : To print the elements of integer array in original order.
import java.util.*;
class GFG {
public static void main(String[] args) {
List<Integer> list = Arrays.asList( 10 , 19 , 20 , 1 , 2 );
list.stream().forEachOrdered(System.out::println);
}
}
|
Example 2 : To print the elements of string array in original order.
import java.util.*;
class GFG {
public static void main(String[] args) {
List<String> list = Arrays.asList( "GFG" , "Geeks" ,
"for" , "GeeksforGeeks" );
list.stream().forEachOrdered(System.out::println);
}
}
|
Output:
GFG
Geeks
for
GeeksforGeeks
Example 3 : To print the characters at index 2 of string array in original order.
import java.util.*;
import java.util.stream.Stream;
class GFG {
public static void main(String[] args) {
Stream<String> stream = Stream.of( "GFG" , "Geeks" ,
"for" , "GeeksforGeeks" );
stream.flatMap(str-> Stream.of(str.charAt( 2 )))
.forEachOrdered(System.out::println);
}
}
|