| by Arround The Web | No comments

How to Use Collectors groupingBy() Method in Java?

The Collectors “groupingBy()” method is utilized to perform grouping operations on data available in a stream and collects the results. It uses “Map” for storing collected results. It helps in the process of organizing and aggregating data based on particular criteria. The Stream Collectors “groupingBy()” method can be widely utilized for the process of “Reporting”, “Aggregation”, and “Data Analysis”.

This article demonstrates the procedure for using the collectors groupingBy() method in Java.

How to Use Collectors groupingBy() Method in Java?

The Collectors groupingBy() method enables users to define complex grouping logic. It can seamlessly integrate with the Stream API, enabling efficient and concise stream processing operations. The collector “groupingBy()” method returns the grouping key mapped to a list of elements that share the same key.

Syntax

The syntax of the Collector groupingBy() method is stated below:

public static Collector<T, ?, Map<K, List>> groupingBy(Function demo);

Let us break down the syntax and analyze each part:

  • First, the “public static” indicates that the method is accessible from anywhere without requiring an instance of the class.
  • The “Collector” object collects the elements of type “T” (the stream element type).
  • Next, the “groupingBy(Function demo)” specifies that the “groupingBy()” method takes a function parameter named “demo”.
  • <T>” represents the stream being processed and “?” represents an unknown type.
  • After that, the “groupingBy()” method may have some intermediate operations before producing the result.
  • In the end, the “Map<K, List>” represents the keys and values of the List from which the “Map” gets generated.

Let us consider an example for better understanding Collectors groupingBy() method in Java:

Example 1: Collectors groupingBy() Method

Visit the below code block to get the usage and implementation of the Collectors groupingBy() method in Java:

import java.util.*;
import java.util.stream.Collectors;
public class GroupingByEx {
  public static void main(String[] args) {
    List<Witch> actor = Arrays.asList(
      new Witch("Elizabeth", 25),
      new Witch("Roman", 33),
      new Witch("Olsen", 25),
      new Witch("Agent", 33)
    );
    Map<Integer, List<Witch>> actorsAge =
    actor.stream().collect(Collectors.groupingBy(Witch::getAge));

    for (Map.Entry<Integer, List<Witch>> entry: actorsAge.entrySet()) {
    int age = entry.getKey();
    List<Witch> group = entry.getValue();
      System.out.println("Age: " + age + " - " + group);
    }
  }
}

Explanation of the above code:

  • First, create a List named “Witch” and pass the random data in the array.
  • Next, the “stream()” method is utilized for the conversion of list data into the stream. Now, apply the “Collectors.groupingBy()” method to the stream and pass “Witch::getAge” as a classifier function.
  • This creates a map consisting of ages and their corresponding objects which reside inside the list. If more than one object has the same “age” then the objects are written next to each other not separately.
  • In addition, store the result of the above computing in a variable named “actorsAge”.
  • After that, utilize the “for” loop to traverse through the data that is collected and stored on the Map. Also, utilize the HashMap “entrySet()” method to create a set of elements having the same data as “age” in our case.
  • In the end, retrieve the Key which stores age and the corresponding values that consist of list items using the “getKey()” and “getValue()” methods, respectively.
  • In the end, store these retrieved values in variables and display them.

Now, create a Witch class to support/provide the required data to the “main()” method:

class Witch {
 private String identity;
 private int age;
 public Witch(String identity, int age) {
  this.identity = identity;
  this.age = age;
 }
 public int getAge() {
  return age;
 }
 @Override
  public String toString() {
   return identity;
  }
}

Explanation of the above code:

  • First, create “identity” and “age” variables inside the class named “Witch”.
  • Then, set these variables as a value to the class variables
  • Next, create a “getAge()” function that returns the variable “age”.
  • After that, override the “String” type by assigning the “toString()” method next to it. This converts the data into strings and then returns the variable named “identity”.

After the end of the compilation phase:

The above snapshot shows the data that has been grouped and displayed in the format of sets.

Conclusion

The “groupingBy()” method accepts a classifier function as a parameter, and this function determines the grouping key for each object in a stream. The objects or elements that have the same grouping key as values for some variables get grouped. And store the result in the resulting map. This guide has explained the usage of the Collectors groupingBy() method in Java.

Share Button

Source: linuxhint.com

Leave a Reply