Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Java 8 FAQ: Top Questions

10. How do you use Collectors to group and summarize data in Java 8?

The Collectors utility class in Java 8 provides powerful methods to group and summarize data from streams using groupingBy, partitioningBy, summarizing, and more. These help in converting, aggregating, and organizing stream results efficiently.

πŸ—ΊοΈ Step-by-Step Instructions:

  1. Stream a collection using .stream().
  2. Use Collectors.groupingBy() to group elements by a classifier function.
  3. Use Collectors.summarizingInt() or similar to generate statistical summaries.

πŸ“₯ Example Input:

class Person {
  String name;
  String city;
  int age;

  Person(String name, String city, int age) {
    this.name = name;
    this.city = city;
    this.age = age;
  }
}

List people = Arrays.asList(
  new Person("Alice", "NY", 30),
  new Person("Bob", "NY", 25),
  new Person("Charlie", "LA", 35)
);

πŸ† Grouping by City:

Map> grouped =
  people.stream().collect(Collectors.groupingBy(p -> p.city));

βœ… Java 8 Solution:

import java.util.*;
import java.util.stream.*;

public class CollectorExample {
  public static void main(String[] args) {
    List people = Arrays.asList(
      new Person("Alice", "NY", 30),
      new Person("Bob", "NY", 25),
      new Person("Charlie", "LA", 35)
    );

    Map> grouped = people.stream()
      .collect(Collectors.groupingBy(p -> p.city));

    grouped.forEach((city, persons) -> {
      System.out.println(city + ": " + persons.size() + " person(s)");
    });
  }

  static class Person {
    String name;
    String city;
    int age;

    Person(String name, String city, int age) {
      this.name = name;
      this.city = city;
      this.age = age;
    }

    public String toString() {
      return name + " (" + age + ")";
    }
  }
}

πŸ“˜ Detailed Explanation:

  • groupingBy(): Creates a map grouping elements by a classifier function.
  • summarizingInt(): Provides average, min, max, and total count for int properties.
  • partitioningBy(): Separates elements into two groups based on a predicate.

πŸ› οΈ Use Cases:

  • Grouping data by category, type, or status.
  • Calculating statistics like average age, total count.
  • Partitioning data for analysis (e.g., eligible vs non-eligible).