1 List分组--groupBy

版权声明:看什么?6,你和我,走一波! https://blog.csdn.net/qq_31323797/article/details/89316731

1.1 样例

package com.java8.list;

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

/**
 * @author gp6
 * @date 2019-04-15
 */
public class TestList {
    public static void main(String[] args) {
        List<Person> personList = new ArrayList<Person>() {{
            add(new Person(1, "小明", 11, 1));
            add(new Person(2, "小红", 12, 0));
            add(new Person(3, "小兰", 13, 0));
            add(new Person(4, "小强", 14, 0));
            add(new Person(5, "小咪", 10, 1));
            add(new Person(6, "小子", 11, 1));
            add(new Person(7, "小虾", 12, 1));
        }};

        // 列表分组,先根据性别分组,再根据年龄分组
        Map<Integer, Map<Integer, List<Person>>> groupsMap = personList.stream().collect(
                Collectors.groupingBy(Person::getSex,
                        Collectors.groupingBy(Person::getAge)));

        // 两层Map循环,处理结果
        groupsMap.forEach((sex, sexMap) -> sexMap.forEach((age, value) -> {
            System.out.println(value);
        }));
    }
}

1.2 结果解析

结果解析

1.3 实体类

package com.java8.list;


import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

/**
 * @author gp6
 * @date 2019-04-15
 */
@Getter
@Setter
@ToString
public class Person {

    /**
     * id
     */
    private Integer id;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 性别
     */
    private Integer sex;

    public Person() {

    }

    public Person(Integer id, String name, Integer age, Integer sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31323797/article/details/89316731
0条评论
添加一条新回复