有没有办法在每次迭代中获取MultiMap中每个元素的Key-Value对,而不先将它们添加到列表中?
我想实现这样的事情:
(我知道这不起作用)
public class MutliMapTest {
public static void main(String... args) {
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("Fruits", "Bannana");
myMultimap.put("Fruits", "Apple");
myMultimap.put("Fruits", "Pear");
myMultimap.put("Vegetables", "Carrot");
Iterator it = myMultimap.keySet().iterator();
while(it.hasNext()) {
String type = it.next().toString();
String name = myMultimap.gettype); // This will get me a List, but I want a single element
System.out.println("Iteration : " + type + " : " + name)
}
}
}
我想要一些类似于:
的输出Iteration : Fruits : Bannana
Iteration : Fruits : Apple
Iteration : Fruits : Pear
Iteration : Vegetables : Carrot
答案 0 :(得分:3)
这似乎可以做你想要的:
public void test() {
System.out.println("Hello");
Multimap<String, String> myMultimap = ArrayListMultimap.create();
// Adding some key/value
myMultimap.put("Fruits", "Bannana");
myMultimap.put("Fruits", "Apple");
myMultimap.put("Fruits", "Pear");
myMultimap.put("Vegetables", "Carrot");
for (Map.Entry<String, String> e : myMultimap.entries()) {
System.out.println("K : " + e.getKey() + " V : " + e.getValue());
}
}
打印
K : Vegetables V : Carrot
K : Fruits V : Bannana
K : Fruits V : Apple
K : Fruits V : Pear
答案 1 :(得分:2)
我认为entries
方法符合您的要求
假设您正在谈论MultiMap的Google Guava变体
答案 2 :(得分:1)
Multimap
是密钥的Map
- &gt;集合,对于这样的类,在适当的集合上使用嵌套的foreach循环:
Multimap<String, String> myMultimap;
for (Map.Entry<String, List<String>> entry : myMultimap.entrySet()) {
for (String value ; entry.getValue()) {
System.out.println(entry.getKey() + ":" + value);
}
}