Close

Java 8 Streams - Stream.forEachOrdered Examples

Java 8 Streams Java Java API 


Interface:

java.util.stream.Stream

java.lang.AutoCloseableAutoCloseablejava.util.stream.BaseStreamBaseStreamjava.util.stream.StreamStreamLogicBig

Method:

void forEachOrdered(Consumer<? super T> action)

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.


Examples


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




See Also