How to Use Collectors in Java 8

  • google plus

In Brief...

The Collectors class in Java 8 provides methods to compute statistics on data. A representative method is summarizingInt that accepts a lambda expression or method reference as its argument. The argument indicates the data from which statistics are to be computed. This method returns an IntSummaryStatistics object that contains the statistics. To learn how to use collectors, follow these four steps.

Take our Introduction to Java Training course for free.

See the Course Outline and Register

Instructions

  1. Open your text editor and create the Java program that will create the stream and collect statistics. Type in the following Java statements:
    import java.util.stream.*;
    import java.util.function.*;
    import java.util.*;
    public class UsingCollectors {
    	private static List numbers=new ArrayList<>();
    	static {
    		numbers.add(50);
    		numbers.add(1);
    		numbers.add(204);
    		numbers.add(-27);
    		numbers.add(27);
    		numbers.add(-204);
    		numbers.add(9);
    		numbers.add(40);
    	}
    	public static void main (String args[]) {
    		System.out.println("The list of integers:");
    		numbers.stream().forEach(System.out::println);
    		IntSummaryStatistics numberOfElements=numbers.stream().collect(Collectors.summarizingInt(x -> x ) ) ;
    		System.out.println("Statistics follow:");
    		System.out.println(numberOfElements);
    		System.out.println("Minimum: " + numberOfElements.getMin());
    		System.out.println("Maximum: " + numberOfElements.getMax());
    		System.out.println("Sum: " + numberOfElements.getSum());
    		System.out.println("Count: " + numberOfElements.getCount());
    		System.out.println("Average: " + numberOfElements.getAverage());
    	}
    }
    The stream will be created from the ArrayList that is defined on line 5. Note that a static block is used to add elements to the ArrayList. A static block is executed one time when the program is loaded into memory. The program will display the list of integers and then apply the Collectors method to gather statistics. Note the use of the collect method that is used to invoke the Collectors method named summarizingInt. A lambda expression is passed to this method to indicate we wish to gather statistics based on the integers in the list. The method returns an object of type IntSummaryStatistics. The program displays the IntSummaryStatistics object. This object has a toString method that displays all of the statistics. Next, the program displays the statistics individually using the appropriate getter method. I have highlighted the summarizingInt method call in the image below:
    Java Source for Collectors Operations
  2. Save your file as UsingCollectors.java.
  3. Open a command prompt and navigate to the directory containing your new Java program. Then type in the command to compile the source and hit Enter.
    Compile Program with Collectors Operations
  4. You are ready to test your Java program. Type in the command to run the Java runtime launcher and hit Enter.
    Run Program with Collectors Operations
    The output displays the collection of integers, followed by the output from displaying the IntSummaryStatistics variable. Next, the program displays the minimum value, the maximum value, the sum, the count, and the average of the integers in the collection.

Author: Stephen Withrow

Stephen has over 30 years' experience in training, development, and consulting in a variety of technology areas including Java, C, C++, XML, JavaScript, AJAX, Tomcat, JBoss, Oracle, and DB2. His background includes design and implementation of business solutions on client/server, Web, and enterprise platforms. Stephen is a published writer in both technical and non-technical endeavors. Stephen received an undergraduate degree in Computer Science and Physics from Florida State University.

Discuss