标签:
每个有经验的Java程序员都在某处实现过Map<K, List<V>>或Map<K, Set<V>>,并且要忍受这个结构的笨拙。
假如目前有个需求是给两个年级添加5个学生,并且统计出一年级学生的信息:
public class MultimapTest { class Student { String name; int age; } private static final String CLASS_NAME_1 = "一年级"; private static final String CLASS_NAME_2 = "二年级"; Map<String, List<Student>> StudentsMap = new HashMap<String, List<Student>>(); public void testStudent() { for (int i = 0; i < 5; i++) { Student student = new Student(); student.name = "Tom" + i; student.age = 6; addStudent(CLASS_NAME_1, student); } for (int i = 0; i < 5; i++) { Student student = new Student(); student.name = "Jary" + i; student.age = 7; addStudent(CLASS_NAME_2, student); } List<Student> class1StudentList = StudentsMap.get(CLASS_NAME_1); for (Student stu : class1StudentList) { System.out.println("一年级学生 name:" + stu.name + " age:" + stu.age); } } public void addStudent(String className, Student student) { List<Student> students = StudentsMap.get(className); if (students == null) { students = new ArrayList<Student>(); StudentsMap.put(className, students); } students.add(student); } public static void main(String[] args) { MultimapTest multimapTest = new MultimapTest(); multimapTest.testStudent(); } }
可以看到我们实现起来特别麻烦,需要检查key是否存在,不存在时则创建一个,存在时在List后面添加上一个。这个过程是比较痛苦的,如果希望检查List中的对象是否存在,删除一个对象,或者遍历整个数据结构,那么则需要更多的代码来实现。
Multimap 提供了一个方便地把一个键对应到多个值的数据结构。
我们可以这样理解Multimap:”键-单个值映射”的集合(例如:a -> 1 a -> 2 a ->4 b -> 3 c -> 5)
特点:不会有任何键映射到空集合:一个键要么至少到一个值,要么根本就不在Multimap中。
Multimap还支持若干强大的视图:
Multimap<K, V>不是Map<K,Collection<V>>,虽然某些Multimap实现中可能使用了map。它们之间的显著区别包括:
import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; public class MultimapTest { class Student { String name; int age; } private static final String CLASS_NAME_1 = "一年级"; private static final String CLASS_NAME_2 = "二年级"; Multimap<String, Student> multimap = ArrayListMultimap.create(); public void testStudent() { for (int i = 0; i < 5; i++) { Student student = new Student(); student.name = "Tom" + i; student.age = 6; multimap.put(CLASS_NAME_1, student); } for (int i = 0; i < 5; i++) { Student student = new Student(); student.name = "Jary" + i; student.age = 7; multimap.put(CLASS_NAME_2, student); } for (Student stu : multimap.get(CLASS_NAME_1)) { System.out.println("一年级学生 name:" + stu.name + " age:" + stu.age); } //判断键是否存在 if(multimap.containsKey(CLASS_NAME_1)){ System.out.println("键值包含:"+CLASS_NAME_1); } //”键-单个值映射”的个数 System.out.println(multimap.size()); //不同键的个数 System.out.print(multimap.keySet().size()); } public static void main(String[] args) { MultimapTest multimapTest = new MultimapTest(); multimapTest.testStudent(); } }
[Google Guava]学习--新集合类型Multimap
标签:
原文地址:http://www.cnblogs.com/parryyang/p/5776654.html