关于JAVA stream根据类型分组数据

废话不说,直接上代码

    public static void main(String[] args) {
        List<Map<String,ScheduleDTO>> map = new ArrayList<>();
        List<ScheduleDTO> list = new ArrayList<>();
        for (int i = 0; i < 2 ; i++) {
            for (int j = 0; j <4 ; j++) {
                ScheduleDTO scheduleDTO = new ScheduleDTO();
                scheduleDTO.setState(i+"");
                scheduleDTO.setType(j+"");
                list.add(scheduleDTO);
            }
        }
        Map<String, List<ScheduleDTO>> collect = list.stream().collect(Collectors.groupingBy(ScheduleDTO::getState, Collectors.toList()));

        System.out.println(JSONObject.toJSONString(collect));
    }

分组的数据

{
    "0":[
        {
            "state":"0",
            "type":"0"
        },
        {
            "state":"0",
            "type":"1"
        },
        {
            "state":"0",
            "type":"2"
        },
        {
            "state":"0",
            "type":"3"
        }
    ],
    "1":[
        {
            "state":"1",
            "type":"0"
        },
        {
            "state":"1",
            "type":"1"
        },
        {
            "state":"1",
            "type":"2"
        },
        {
            "state":"1",
            "type":"3"
        }
    ]
}

Guess you like

Origin blog.csdn.net/qq_39164154/article/details/114756951