2015-06-25 47 views
2

我有以下方法:如何使用Guava的MultiMap输出唯一的密钥? (JAVA)

public static void showStuff(Multimap<String, String> map) { 
     for (String key : map.keys()) { 
      System.out.println("The key, " + key 
        + ", has the results: " + map.get(key)); 
     } 
    } 

此输出:

The key, **one**, has the results: [a,b,c,d,d,e] 
The key, **one**, has the results: [a,b,c,d,d,e] 
The key, **one**, has the results: [a,b,c,d,d,e] 
The key, **one**, has the results: [a,b,c,d,d,e] 
The key, **one**, has the results: [a,b,c,d,d,e] 
The key, **two**, has the results: [a,a,a,b,b,e] 
The key, **two**, has the results: [a,a,a,b,b,e] 

我怎么会有它只能输出唯一的密钥。我希望它只打印一次陈述,而不是多次重复陈述。我有一个包含重复键的不同行的表,因此我使用MultiMap获取重复键的所有值。我现在将如何输出

The key, **one**, has the results: [a,b,c,d,d,e] 
The key, **two**, has the results: [a,a,a,b,b,e] 

谢谢!

回答

6

您可以使用Multimap.keySet()得到公正的区别键。

您可以使用Multimap.entries()获取(键,值)对,而不必返回到映射以请求与每个键相关联的值。

或者,您可以使用Multimap.asMap()将其转换为java.util.Map,然后改用它。

1

使用map.keySet(),而不是map.keys()