Google Guava MultiMap我不知道如何访问我的对象

时间:2017-01-29 18:44:46

标签: java collections guava

我创建了一个hashmultimap 如何使用迭代器访问hashmultimap中的Student对象?

Multimap<Integer, Object> myMultimap2 = HashMultimap.create();
Student one = new Student("Bob","Any",35);
Student two = new Student("Tom","Johnson",22);
Student three = new Student("Yo","Zun",42);
myMultimap2.put(1,one);
myMultimap2.put(2,two);
myMultimap2.put(2,three);
Iterator<Integer> iterator = myMultimap2.keySet().iterator();

while (iterator.hasNext()){
    int key = iterator.next();
    System.out.println(key);
    Collection collection = myMultimap2.get(key);
    Iterator iterator2 = collection.iterator();
    while (iterator2.hasNext()){
        System.out.println(iterator2.next());
        ???????
    }
}

1 个答案:

答案 0 :(得分:1)

Guava&#39; Multimap为每个密钥保留Collection个值。 因此,您的第二个迭代器Object返回的iterator2实际上是您之前放置的Student

使用正确的泛型可能更有意义,即将Multimap声明为Multimap<Integer, Student>。然后你的第二个迭代器将返回Student而不是Object