How to Use Parallel Processing on Streams in Java 8

Java 8 streams can be processed in parallel. When processed in parallel, a stream is divided into substreams. Each substream is processed in parallel on separate CPUs (if available on the computer). Aggregate functions such as count or sum are suitable for parallel processing. The Java runtime environment will process each substream and apply the aggregate operation. When the substreams have been processed, the intermediate results will be merged to produce a final result. To learn how to use parallel processing on streams in Java 8, follow these four steps.

  1. Open your text editor and create the Java program that will use parallel processing to compute a count of names in a collection. Type in the following Java statements:
    import java.util.*;
    public class ParallelProcessingUsingStreams {
    	private static List names=new ArrayList<>();
    	static {
    	public static void main (String args[]) {
    		Console console=System.console();
    		int userLimit=Integer.parseInt(console.readLine("Please enter the minimum number of characters in the name: "));
    		long count=names.parallelStream().filter(name -> name.length()>=userLimit).count();
    		System.out.format("Count of names that have at least %d characters: %d\n", userLimit, count);
    		System.out.format("Names that have at least %d characters: \n", userLimit); -> name.length()>=userLimit).forEach(System.out::println);
    The stream will be created from the ArrayList of person names that is defined on line 5. The program prompts the user to enter the minimum number of characters required in the name. The program will then use parallel stream processing to determine the count of names whose number of characters is greater than or equal to the number entered by the user. Note that parallel processing is specified using the parallelStream method. The count is displayed on the console. The program also displays the names that meet the criteria. I have highlighted the parallel stream method in the image below:
    Java Source for Parallel Processing
  2. Save your file as
    Compile Program with Parallel Processing
  4. You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter. Type "4" when prompted for the number of characters in the name. The output displays the count of names that meet the criteria followed by the list of names.
    Run Program with Parallel Processing
Author: Stephen Withrow


About Webucator
