package stream;

import lombok.Getter;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class StreamExample08 {

    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("Alice", 30),
                new Person("Bob", 25),
                new Person("Charlie", 30),
                new Person("David", 25)
        );

        // 根据年龄将一组人分组
        Map<Integer, List<Person>> groupedByAge = people.stream()
                .collect(Collectors.groupingBy(Person::getAge));
        System.out.println(groupedByAge);

        // 自定义收集器：可以传递第二个参数来指定下游收集器。
        Map<Integer, Long> groupedByAgeCount = people.stream()
                .collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
        System.out.println(groupedByAgeCount);

        // 多级分组：可以嵌套使用 groupingBy 进行多级分组。
        Map<Integer, Map<String, List<Person>>> groupedByAgeAndName = people.stream()
                .collect(Collectors.groupingBy(Person::getAge, Collectors.groupingBy(Person::getName)));
        System.out.println(groupedByAgeAndName);
    }

    @Getter
    static class Person {
        private final String name;
        private final int age;

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

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