简体   繁体   English

Multimap如何从键返回所有值

[英]Multimap how to return all values from a key

Multimaps can have multiple values how would I be able to return all the values from a key if it contains multiple values. 多图可以具有多个值,如果键包含多个值,我将如何从键中返回所有值。

Multimap<String, String> wordcount = ArrayListMultimap.create();

wordcount.put("1", "Dog");
wordcount.put("1", "Dog2");
wordcount.put("1", "Dog3");

So you can see above I gave my Multimap key "1" the following values "Dog", "Dog2" & "Dog3" how would I be able to print out all the dogs? 因此,您可以在上方看到我为Multimap键“ 1”提供了以下值“ Dog”,“ Dog2”和“ Dog3”,我该如何打印出所有狗?

Extra Questions How would I be able to check if a key contains multiple values of the same string for that specific key? 额外问题我如何才能检查某个键是否包含该特定键的同一字符串的多个值? Also how would I be able to return the amount of "same" strings it contains. 另外,我将如何返回其中包含的“相同”字符串的数量。 It should return 3 because I specified the value 3 times with the same value so it should return 3 . 它应该返回3,因为我用相同的值指定了3次该值,所以它应该返回3

wordcount.put("1", "Dog");
wordcount.put("1", "Dog");
wordcount.put("1", "Dog");

You can just do wordcount.get("1") it will return a List containing Dog1, Dog2, Dog3 您只需执行wordcount.get("1") ,它将返回一个包含Dog1, Dog2, Dog3的列表

For your extra question: I think you have to do wordcount.get("1") to get the List object and iterate through the list object if you want to use an ArrayListMultimap instance. 对于您的其他问题:我想您必须执行wordcount.get("1")才能获取List对象,并在要使用ArrayListMultimap实例的情况下遍历list对象。

Alternatively, you may want to checkout Multiset<String> that keeps track of number of occurrences of your input Strings. 另外,您可能希望检出Multiset<String> ,以跟踪输入字符串的出现次数。 In this case you can use Map<String, Multiset<String>> instead of ArrayListMultimap instance to avoid iterating the returned list. 在这种情况下,可以使用Map<String, Multiset<String>>而不是ArrayListMultimap实例来避免迭代返回的列表。

But Multiset<?> is a set so it does not iterate in the order you put the values. 但是Multiset<?>是一个集合,因此它不会按照放置值的顺序进行迭代。

The get method returns a list of values for a given key. get方法返回给定键的值列表。 You could just rely on the returned List 's toString() : 您可以仅依靠返回的ListtoString()

System.out.println(wordcount.get("1"));

Or just iterate over them and print each one separately: 或者只是遍历它们并分别打印每个:

for (String s : wordcount.get("1")) {
    System.out.println(s);
}

Or join all the values in that list to a single string somehow, eg, by using a Joiner : 或以某种方式将列表中的所有值连接到单个字符串,例如,使用Joiner

System.out.println(Joiner.on(",").join(wordcount.get("1"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM