Collectors.groupingBy对List集合进行分组

package com.xxx.xxx.xxx;

import com.alibaba.fastjson.JSON;

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

public class TestDemo {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();
        Student student1 = new Student("张三", "踢球");
        Student student2 = new Student("李四", "滑雪");
        Student student3 = new Student("王五", "看电视");
        Student student4 = new Student("赵六", "踢球");
        list.add(student1);
        list.add(student2);
        list.add(student3);
        list.add(student4);
        Map<String, List<Student>> listMap = list.stream().collect(Collectors.groupingBy(student -> student.getHobby()));
        System.out.println(JSON.toJSONString(listMap));
    }

    static class Student {
        private String hobby;
        private String name;

        public Student(String name, String hobby) {
            this.hobby = hobby;
            this.name = name;
        }

        public String getHobby() {
            return hobby;
        }

        public void setHobby(String hobby) {
            this.hobby = hobby;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}


结果:

{"踢球":[{"hobby":"踢球","name":"张三"},{"hobby":"踢球","name":"赵六"}],"看电视":[{"hobby":"看电视","name":"王五"}],"滑雪":[{"hobby":"滑雪","name":"李四"}]}

你可能感兴趣的:(java相关,开发语言,java)