Pages

Collectors Class

Collectors is a final class that extends Object class and all the methods are static that returns the Collector instance. It provides reduction operations. All predefined implementations can be found in the Collectors class. Stream.collect() method, Collector interface and Collectors class. collect() method is a terminal operation in Stream interface. Collector is an interface in java.util.stream package. Collectors class, also a member of java.util.stream package, is an utility class containing many static methods which perform some common reduction operations.


1. Stream.collect() Method

collect() method is a terminal operation in Stream interface. It is a special case of reduction operation called mutable reduction operation because it returns mutable result container such as List, Set or Map according to supplied Collector.


2. java.util.stream.Collector Interface

java.util.stream.Collector interface contains four functions that work together to accumulate input elements into a mutable result container and optionally performs a final transformation on the result.

2.1. Supplier() : Supplier function that creates and returns a new mutable result container.
2.2. accumulator() : accumulator function that accumulates a value into a mutable result container.
2.3. combiner() : combiner function that accepts two partial results and merges them.
2.4. finisher() : finisher function that performs final transformation from the intermediate accumulation type to the final result type.

3. java.util.stream.Collectors Class

java.util.stream.Collectors class contains static factory methods which perform some common reduction operations such as accumulating elements into Collection, finding min, max, average, sum of elements etc. All the methods of Collectors class return Collector type which will be supplied to collect() method as an argument.

3.1. toList() : toList() method returns a Collector which collects all input elements into a new List.
3.2. toSet() : toSet method returns a Collector which collects all input elements into a new Set.
3.3. toMap() : toMap method returns a Collector which collects input elements into a Map whose keys and values are the result of applying mapping functions to input elements.
3.4. toCollection() : toCollection method returns a Collector which collects all input elements into a new Collection.
3.5. joining() : joining method returns a Collector which concatenates input elements separated by the specified delimiter.
3.6. counting() : counting method returns a Collector that counts number of input elements.
3.7. maxBy() : maxBy method returns a Collector that collects largest element in a stream according to supplied Comparator.
3.8. minBy() : minBy method returns a Collector which collects smallest element in a stream according to supplied Comparator.
3.9. summingInt() : summingInt methods returns a Collector which collects sum of all integer input elements.
3.10. summingLong() : summingLong methods returns a Collector which collects sum of all long input elements.
3.11. summingDouble() : summingDouble methods returns a Collector which collects sum of all double input elements.
3.12. averagingInt() : averagingInt methods return a Collector which collects average of integer input elements.
3.13. averagingLong() : averagingLong methods return a Collector which collects average of long input elements.
3.14. averagingDouble() : averagingDouble methods return a Collector which collects average of double input elements.
3.15. summarizingInt() : summarizingInt methods return a special class called IntSummaryStatistics which contain statistical information like sum, max, min, average etc of integer input elements.
3.16. summarizingLong() : summarizingLong methods return a special class called LongSummaryStatistics which contain statistical information like sum, max, min, average etc of long input elements.
3.17. summarizingDouble() : summarizingDouble methods return a special class called DoubleSummaryStatistics which contain statistical information like sum, max, min, average etc of double input elements.
3.18. groupingBy() : groupingBy method groups the input elements according supplied classifier and returns the results in a Map.
3.19. partitioningBy() : partitioningBy method partitions the input elements according to supplied Predicate and returns a Map. Under the true key, you will find elements which match given Predicate and under the false key, you will find the elements which doesn’t match given Predicate.
3.20. collectingAndThen() : collectingAndThen method is a special method which lets you to perform one more action on the result after collecting the result.

All Methods Example in Collector Class

package com.jaladhi;
public class Student {
      private int id;
      private String name;
      private String subject;
      private double per;
      public Student(int id, String name, String subject, double per) {
            this.id = id;
            this.name = name;
            this.subject = subject;
            this.per = per;
      }
      public int getId() {
            return id;
      }
      public void setId(int id) {
            this.id = id;
      }
      public String getName() {
            return name;
      }
      public void setName(String name) {
            this.name = name;
      }
      public String getSubject() {
            return subject;
      }
      public void setSubject(String subject) {
            this.subject = subject;
      }
      public double getPer() {
            return per;
      }
      public void setPer(double per) {
            this.per = per;
      }
}

package com.jaladhi;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.DoubleSummaryStatistics;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
public class CollectorsExample {
      public static void main(String[] args) {
            List<Student> list = new ArrayList<Student>();
            list.add(new Student(1001, "Biden", "CSE", 78.9));
            list.add(new Student(1002, "Richard", "EEE", 91.2));
            list.add(new Student(1003, "Philly", "ECE", 83.7));
            list.add(new Student(1004, "Terry", "CE", 71.5));
            list.add(new Student(1005, "Clarin", "ME", 77.5));
            list.add(new Student(1006, "Johne", "BME", 89.4));
            list.add(new Student(1007, "River", "EE", 84.6));
            list.add(new Student(1008, "Gladin", "PE", 73.5));
            list.add(new Student(1009, "Alender", "WRE", 92.8));
            list.add(new Student(1010, "Bendern", "GTE", 71.9));
            // Collecting top 3 performing students into List
            List top3Students = list.stream().sorted(Comparator.comparingDouble(Student::getPer).reversed()).limit(3).collect(Collectors.toList());
            System.out.println(top3Students);
            // Collecting subjects offered into Set.
            Set subjects = list.stream().map(Student::getSubject).collect(Collectors.toSet());
            System.out.println(subjects);
            // Collecting name and percentage of each student into a Map
            Map namePercentageMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getPer));
            System.out.println(namePercentageMap);
            // Collecting first 3 students into LinkedList
            LinkedList studentLinkedList = list.stream().limit(3).collect(Collectors.toCollection(LinkedList::new));
            System.out.println(studentLinkedList);
            // Collecting the names of all students joined as a string
            String namesJoined = list.stream().map(Student::getName).collect(Collectors.joining(", "));
            System.out.println(namesJoined);
            // Counting number of students.
            Long studentCount = list.stream().collect(Collectors.counting());
            System.out.println(studentCount);
            // Collecting highest percentage.
            Optional highPercentage = list.stream().map(Student::getPer).collect(Collectors.maxBy(Comparator.naturalOrder()));
            System.out.println(highPercentage);
            // Collecting lowest percentage.
            Optional lowPercentage = list.stream().map(Student::getPer).collect(Collectors.minBy(Comparator.naturalOrder()));
            System.out.println(lowPercentage);
            // Collecting sum of percentages.
            Double sumOfPercentages = list.stream().collect(Collectors.summingDouble(Student::getPer));
            System.out.println(sumOfPercentages);
            // Collecting average percentage.
            Double averagePercentage = list.stream().collect(Collectors.averagingDouble(Student::getPer));
            System.out.println(averagePercentage);
            // Extracting highest, lowest and average of percentage of students.
            DoubleSummaryStatistics studentStats = list.stream().collect(Collectors.summarizingDouble(Student::getPer));
            System.out.println("Highest Percentage : " + studentStats.getMax());
            System.out.println("Lowest Percentage : " + studentStats.getMin());
            System.out.println("Average Percentage : " + studentStats.getAverage());
            // Grouping the students by subject.
            Map studentsGroupedBySubject = list.stream().collect(Collectors.groupingBy(Student::getSubject));
            System.out.println(studentsGroupedBySubject);
            // Partitioning the students who got above 80.0% from who don’t.
            Map studentspartionedByPercentage = list.stream().collect(Collectors.partitioningBy(student -> student.getPer() > 80.0));
            System.out.println(studentspartionedByPercentage);
            // Collecting first three students into List and making it unmodifiable
            List first3Students = list.stream().limit(3).collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
            System.out.println(first3Students);
      }
}