Guava学习——集合Multimap

时间:2021-11-25 17:06:37

在实际业务中,可能会遇到这样的情况,一个Key对应多个Value,比如学校与班级,班级与学生;于是有了下面的代码:

{
Map<Grade, List<Student>> gradeStudents;
Map<School, List<Grade>> schoolGrades;
}
class Student {}
class School {}
class Grade {}

OK,现在开始维护这个数据结构——Map < Object,List>,常规的put,delete操作:

    public void put(Grade grade, Student student) {
List<Student> studentList;
if (!gradeStudents.containsKey(grade)) {
studentList = Lists.newArrayList();
} else {
studentList = gradeStudents.get(grade);
}

if (!studentList.contains(student)) {
studentList.add(student);
}
gradeStudents.put(grade, studentList);
}

public void remove(Grade grade,Student student){
if(gradeStudents.containsKey(grade)){
List<Student> studentList = gradeStudents.get(grade);
studentList.remove(student);
}
}

还有get、contains操作,可以想象维护工作是多么的痛苦! 还好Guava提供了一个数据结构Multimap,通过它,我们可以方便的管理、使用这样的多个key/value映射的情况。
下面看下它的结构:
Guava学习——集合Multimap
使用它来完成上面的情景:

        Multimap<Grade, Student> multimap = HashMultimap.create();
Grade grade = new Grade();
Student student = new Student();

//新增
multimap.put(grade, student);
//删除一个映射
multimap.remove(grade, student);
//删除所有grade映射
multimap.removeAll(grade);
//获得grade所有的映射
Collection<Student> students = multimap.get(grade);
for (Student s : students) {
System.out.println(s);
}