美文网首页
将list的内容分组(根据实体的属性)

将list的内容分组(根据实体的属性)

作者: junjun2018 | 来源:发表于2018-07-25 13:44 被阅读0次

先整个实体

public class Student {
    private String name;
    private Integer age;

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

    public String getName() {
        return name;
    }

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

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

分组实现

public class ListGroup {
    public static void main(String[] args) {
        Student student = new Student("ysj", 22);
        Student student1 = new Student("lt", 23);
        Student student2 = new Student("ysj", 18);
        Student student3 = new Student("cc", 28);

        ArrayList<Student> list = new ArrayList<>();
        list.add(student);
        list.add(student1);
        list.add(student2);
        list.add(student3);
        //遍历看一下
        Map<String, List<Student>> listGroup = getListGroup(list);
        for (Map.Entry<String, List<Student>> entry : listGroup.entrySet()) {
            System.out.println(entry.getKey() + "==》" + entry.getValue());
        }

    }
    //分组方法
    private static Map<String, List<Student>> getListGroup(List<Student> list) {
        HashMap<String, List<Student>> ret = new HashMap<>();
        //同名的分为一组
        for (int i = 0; i < list.size(); i++) {
            Student student = list.get(i);
            //如果不存在实体字段的键,则创建一个list,并将list添加至map
            if (!ret.containsKey(student.getName())) {
                ArrayList<Student> li = new ArrayList<>();
                li.add(student);
                ret.put(student.getName(), li);
            } else {
                //如果存在,则直接在list中添加一个即可
                ret.get(student.getName()).add(student);
            }
        }

        return ret;
    }

}
//结果
cc ==》[Student{name='cc', age=28}]
ysj ==》[Student{name='ysj', age=22}, Student{name='ysj', age=18}]
lt ==》[Student{name='lt', age=23}]

相关文章

网友评论

      本文标题:将list的内容分组(根据实体的属性)

      本文链接:https://www.haomeiwen.com/subject/viepmftx.html