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:
- Stream a collection using
.stream()
. - Use
Collectors.groupingBy()
to group elements by a classifier function. - 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).