Java Collectors class

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Java Collectors

Collectors is a final class that extends Object class. It provides reduction operations, such as accumulating elements into collections, summarizing elements according to various criteria, etc.

Java Collectors class provides various methods to deal with elements

Methods

Description

public static Collector averagingDouble(ToDoubleFunction mapper)

It returns a Collector that produces the arithmetic mean of a double-valued function applied to the input elements. If no elements are present, the result is 0.

public static Collector reducing(T identity, BinaryOperator op)

It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator using the provided identity.

public static Collector> reducing(BinaryOperator op)

It returns a Collector which performs a reduction of its input elements under a specified BinaryOperator. The result is described as an Optional.

public static Collector reducing(U identity, Function mapper, BinaryOperator op)

It returns a Collector which performs a reduction of its input elements under a specified mapping function and BinaryOperator. This is a generalization of reducing(Object, BinaryOperator) which allows a transformation of the elements before reduction.

public static Collector>> groupingBy(Function classifier)

It returns a Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function, and returning the results in a Map.

public static Collector> groupingBy(Function classifier, Collector downstream)

It returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

public static > Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream)

It returns a Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. The Map produced by the Collector is created with the supplied factory function.

public static Collector>> groupingByConcurrent(Function classifier)

It returns a concurrent Collector implementing a "group by" operation on input elements of type T, grouping elements according to a classification function.

public static Collector> groupingByConcurrent(Function classifier, Collector downstream)

It returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector.

public static > Collector groupingByConcurrent(Function classifier, Supplier mapFactory, Collector downstream)

It returns a concurrent Collector implementing a cascaded "group by" operation on input elements of type T, grouping elements according to a classification function, and then performing a reduction operation on the values associated with a given key using the specified downstream Collector. The ConcurrentMap produced by the Collector is created with the supplied factory function.

public static Collector>> partitioningBy(Predicate predicate)

It returns a Collector which partitions the input elements according to a Predicate, and organizes them into a Map>. There are no guarantees on the type, mutability, serializability, or thread-safety of the Map returned.

public static Collector> partitioningBy(Predicate predicate, Collector downstream)

It returns a Collector which partitions the input elements according to a Predicate, reduces the values in each partition according to another Collector, and organizes them into a Map whose values are the result of the downstream reduction.

public static Collector> toMap(Function keyMapper, Function valueMapper)

It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

public static Collector> toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

public static > Collector toMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)

It returns a Collector that accumulates elements into a Map whose keys and values are the result of applying the provided mapping functions to the input elements.

public static Collector> toConcurrentMap(Function keyMapper, Function valueMapper)

It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

public static Collector> toConcurrentMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction)

It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

public static > Collector toConcurrentMap(Function keyMapper, Function valueMapper, BinaryOperator mergeFunction, Supplier mapSupplier)

It returns a concurrent Collector that accumulates elements into a ConcurrentMap whose keys and values are the result of applying the provided mapping functions to the input elements.

public static Collector summarizingInt(ToIntFunction mapper)

It returns a Collector which applies an int-producing mapping function to each input element, and returns summary statistics for the resulting values.

public static Collector summarizingLong(ToLongFunction mapper)

It returns a Collector which applies an long-producing mapping function to each input element, and returns summary statistics for the resulting values.

public static Collector summarizingDouble(ToDoubleFunction mapper)

It returns a Collector which applies an double-producing mapping function to each input element, and returns summary statistics for the resulting values.

Java Collectors Example: Fetching data as a List

  1. import java.util.stream.Collectors;  
  2. import java.util.List;  
  3. import java.util.ArrayList;  
  4. class Product{  
  5.     int id;  
  6.     String name;  
  7.     float price;  
  8.       
  9.     public Product(int id, String name, float price) {  
  10.         this.id = id;  
  11.         this.name = name;  
  12.         this.price = price;  
  13.     }  
  14. }  
  15. public class CollectorsExample {  
  16.     public static void main(String[] args) {  
  17.         List<Product> productsList = new ArrayList<Product>();  
  18.         //Adding Products  
  19.         productsList.add(new Product(1,"HP Laptop",25000f));  
  20.         productsList.add(new Product(2,"Dell Laptop",30000f));  
  21.         productsList.add(new Product(3,"Lenevo Laptop",28000f));  
  22.         productsList.add(new Product(4,"Sony Laptop",28000f));  
  23.         productsList.add(new Product(5,"Apple Laptop",90000f));  
  24.         List<Float> productPriceList =   
  25.                 productsList.stream()  
  26.                             .map(x->x.price)         // fetching price  
  27.                             .collect(Collectors.toList());  // collecting as list  
  28.         System.out.println(productPriceList);  
  29.     }  
  30. }  

Output:

[25000.0, 30000.0, 28000.0, 28000.0, 90000.0]

Java Collectors Example: Converting Data as a Set

 
  1. import java.util.stream.Collectors;  
  2. import java.util.Set;  
  3. import java.util.List;  
  4. import java.util.ArrayList;  
  5. classProduct{  
  6.     intid;  
  7.     String name;  
  8.     floatprice;  
  9.       
  10.     public Product(intid, String name, floatprice) {  
  11.         this.id = id;  
  12.         this.name = name;  
  13.         this.price = price;  
  14.     }  
  15. }  
  16. publicclass CollectorsExample {  
  17.     publicstaticvoid main(String[] args) {  
  18.         List<Product>productsList = new ArrayList<Product>();  
  19.         //Adding Products  
  20.         productsList.add(newProduct(1,"HP Laptop",25000f));  
  21.         productsList.add(newProduct(2,"Dell Laptop",30000f));  
  22.         productsList.add(newProduct(3,"Lenevo Laptop",28000f));  
  23.         productsList.add(newProduct(4,"Sony Laptop",28000f));  
  24.         productsList.add(newProduct(5,"Apple Laptop",90000f));  
  25.         Set<Float>productPriceList =   
  26.                 productsList.stream()  
  27.                             .map(x->x.price)         // fetching price  
  28.                             .collect(Collectors.toSet());   // collecting as list  
  29.         System.out.println(productPriceList);  
  30.     }  
  31. }  

Output:

[25000.0, 30000.0, 28000.0, 90000.0]

Java Collectors Example: using sum method

 
  1. import java.util.stream.Collectors;  
  2. import java.util.List;  
  3. import java.util.ArrayList;  
  4. class Product{  
  5.     int id;  
  6.     String name;  
  7.     float price;  
  8.       
  9.     public Product(int id, String name, float price) {  
  10.         this.id = id;  
  11.         this.name = name;  
  12.         this.price = price;  
  13.     }  
  14. }  
  15. public class CollectorsExample {  
  16.     public static void main(String[] args) {  
  17.         List<Product> productsList = new ArrayList<Product>();  
  18.         //Adding Products  
  19.         productsList.add(new Product(1,"HP Laptop",25000f));  
  20.         productsList.add(new Product(2,"Dell Laptop",30000f));  
  21.         productsList.add(new Product(3,"Lenevo Laptop",28000f));  
  22.         productsList.add(new Product(4,"Sony Laptop",28000f));  
  23.         productsList.add(new Product(5,"Apple Laptop",90000f));  
  24.         Double sumPrices =   
  25.                 productsList.stream()  
  26.                             .collect(Collectors.summingDouble(x->x.price));  // collecting as list  
  27.         System.out.println("Sum of prices: "+sumPrices);  
  28.         Integer sumId =   
  29.                 productsList.stream().collect(Collectors.summingInt(x->x.id));  
  30.         System.out.println("Sum of id's: "+sumId);  
  31.     }  
  32. }  

Output:

Sum of prices: 201000.0
Sum of id's: 15

Java Collectors Example: Getting Product Average Price

 
  1. import java.util.stream.Collectors;  
  2. import java.util.List;  
  3. import java.util.ArrayList;  
  4. class Product{  
  5.     int id;  
  6.     String name;  
  7.     float price;  
  8.       
  9.     public Product(int id, String name, float price) {  
  10.         this.id = id;  
  11.         this.name = name;  
  12.         this.price = price;  
  13.     }  
  14. }  
  15. public class CollectorsExample {  
  16.     public static void main(String[] args) {  
  17.         List<Product> productsList = new ArrayList<Product>();  
  18.         //Adding Products  
  19.         productsList.add(new Product(1,"HP Laptop",25000f));  
  20.         productsList.add(new Product(2,"Dell Laptop",30000f));  
  21.         productsList.add(new Product(3,"Lenevo Laptop",28000f));  
  22.         productsList.add(new Product(4,"Sony Laptop",28000f));  
  23.         productsList.add(new Product(5,"Apple Laptop",90000f));  
  24.         Double average = productsList.stream()  
  25.                          .collect(Collectors.averagingDouble(p->p.price));  
  26.         System.out.println("Average price is: "+average);  
  27.     }  
  28. }  

Output:

Average price is: 40200.0

Java Collectors Example: Counting Elements

 
  1. import java.util.stream.Collectors;  
  2. import java.util.List;  
  3. import java.util.ArrayList;  
  4. class Product{  
  5.     intid;  
  6.     String name;  
  7.     floatprice;  
  8.       
  9.     public Product(intid, String name, floatprice) {  
  10.         this.id = id;  
  11.         this.name = name;  
  12.         this.price = price;  
  13.     }  
  14.     publicint getId() {  
  15.         returnid;  
  16.     }  
  17.     public String getName() {  
  18.         returnname;  
  19.     }  
  20.     publicfloat getPrice() {  
  21.         returnprice;  
  22.     }  
  23. }  
  24. publicclass CollectorsExample {  
  25.     publicstaticvoid main(String[] args) {  
  26.         List<Product>productsList = new ArrayList<Product>();  
  27.         //Adding Products  
  28.         productsList.add(new Product(1,"HP Laptop",25000f));  
  29.         productsList.add(new Product(2,"Dell Laptop",30000f));  
  30.         productsList.add(new Product(3,"Lenevo Laptop",28000f));  
  31.         productsList.add(new Product(4,"Sony Laptop",28000f));  
  32.         productsList.add(new Product(5,"Apple Laptop",90000f));  
  33.         Long noOfElements = productsList.stream()  
  34.                                .collect(Collectors.counting());  
  35.         System.out.println("Total elements : "+noOfElements);  
  36.     }  
  37. }  

Output:

Total elements : 5