Java 8 Stream Example: forEach() vs forEachOrdered()

Java 8 streams provide two methods for iterating over the elements of a stream: forEach() and forEachOrdered(). Both methods take a consumer as an argument, which is a functional interface that accepts a single argument and performs an operation on it.

The main difference between forEach() and forEachOrdered() is that forEach() does not guarantee the order in which the elements of the stream will be processed, while forEachOrdered() does. This is because forEach() is allowed to process the elements of the stream in parallel, while forEachOrdered() is not.

package the.basic.tech.info;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("Java8", "StreamAPI", null, "Test", null);
		List<String> result = list.stream().filter(str -> str != null).collect(Collectors.toList());
		result.parallelStream().forEach(System.out::println);
		
	}

}

Output
StreamAPI
Test
Java8

package the.basic.tech.info;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamExample {

	public static void main(String[] args) {

		List<String> list = Arrays.asList("Java8", "StreamAPI", null, "Test", null);
		List<String> result = list.stream().filter(str -> str != null).collect(Collectors.toList());
		result.parallelStream().forEachOrdered(System.out::println);
	}

}

Output
Java8
StreamAPI
Test