This terminal operation performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order.
package com.logicbig.example.stream;
import java.util.stream.Stream;
public class ForEachOrderedExample {
public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
runForEach(Stream.of(s));
runForEachOrdered(Stream.of(s));
}
private static void runForEach(Stream<String> stream) {
System.out.println("-- running unordered --");
stream.forEach(System.out::println);
}
private static void runForEachOrdered(Stream<String> stream) {
System.out.println("-- running ordered --");
stream.forEachOrdered(System.out::println);
}
}
Output
-- running unordered --
one
two
three
four
-- running ordered --
one
two
three
four
For parallel stream
package com.logicbig.example.stream;
import java.util.stream.Stream;
public class ForEachOrderedExample2 {
public static void main(String... args) {
String[] s = {"one", "two", "three", "four"};
runForEach(Stream.of(s).parallel());
runForEachOrdered(Stream.of(s).parallel());
}
private static void runForEach(Stream<String> stream) {
System.out.println("-- running unordered --");
stream.forEach(System.out::println);
}
private static void runForEachOrdered(Stream<String> stream) {
System.out.println("-- running ordered --");
stream.forEachOrdered(System.out::println);
}
}
Output
-- running unordered --
three
four
one
two
-- running ordered --
one
two
three
four