将list中的数据通过某一个字段来分类存储的实例
现有学生表
public class Student { /** * 班级id */ private String classId; /** * 学生name */ private String name; public Student() { } public Student(String classId, String name) { super(); this.classId = classId; this.name = name; } public String getClassId() { return classId; } public void setClassId(String classId) { this.classId = classId; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
往student里存数据,并通过classId将student的list进行分类
public static void main(String[] args) { List<Student>allData=new ArrayList<Student>(); allData.add(new Student("class1","张三")); allData.add(new Student("class1","李四")); allData.add(new Student("class1","王五")); allData.add(new Student("class2","赵六")); allData.add(new Student("class2","scy")); Map<String, List<Student>>map=new HashMap<String, List<Student>>(); for(Student student:allData){ if(map.get(student.getClassId())==null){ List<Student>list=new ArrayList<Student>(); list.add(student); map.put(student.getClassId(), list); }else{ List<Student>list=map.get(student.getClassId()); list.add(student); } } for (Student stu:map.get("class1")) { System.out.println("班级id为:"+stu.getClassId()+"的"+stu.getName()); } System.out.println("------------------------------"); for (Student stu:map.get("class2")) { System.out.println("班级id为:"+stu.getClassId()+"的"+stu.getName()); } }
输出结果:
班级id为:class1的张三
班级id为:class1的李四
班级id为:class1的王五
------------------------------
班级id为:class2的赵六
班级id为:class2的scy
这样之后,map中key为class1的对象有三个,key为class2的对象有两个,可以通过这样的分类之后再将数据进行插入或修改就很方便了
顺便说一下遍历map,执行插入或修改操作的相关代码:
List<Student> students = new ArrayList<Student>(); Student stu1=new Student(); for (String key : map.keySet()) { for (Student stu2 : map.get(key)) { stu1.setClassId(stu2.getClassId()); stu1.setName(stu2.getName()); students.add(stu1); } addStudent(students);//执行插入方法 students.clear();//插入完后清空,第二次循环在往里面存值 }