简体   繁体   English

为什么番石榴中的MultiMap的size方法返回(非)预期结果?

[英]why is the size method of MultiMap from Guava return (un)expected result?

I am using MultiMap from Guava library. 我正在使用Guava库中的MultiMap I created a sample MultiMap. 我创建了一个示例MultiMap。 when I print the size of map, I get 4 but the actual value (I think) should be 2. why is this discrepancy? 当我打印地图的大小时,我得到4但实际值(我认为)应为2。为什么会有这种差异?

   import java.util.Collection;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

public class MultiMapTest {
    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");

  System.out.println(myMultimap);

  // Getting the size
  int size = myMultimap.size();
  System.out.println(size);  // 4

  // Getting values
  Collection<String> fruits = myMultimap.get("Fruits");
  System.out.println(fruits); // [Bannana, Apple, Pear]

  Collection<String> vegetables = myMultimap.get("Vegetables");
  System.out.println(vegetables); // [Carrot]

 }
}

Output: 输出:

Fruits=[Bannana, Apple, Pear], Vegetables=[Carrot]}
4
[Bannana, Apple, Pear]
[Carrot]

Here is the output: 这是输出:

From the ArrayListMultiMap docs , this should return the number of key-value pairs in the multimap. ArrayListMultiMap文档中 ,这应该返回多重映射中的键/值对的数量。 But I don't see it. 但是我看不到。

From Guava's API docs , Guava的API文档中

int size() int size()

Returns the number of key-value pairs in this multimap. 返回此多重映射中的键值对的数量。 Note: this method does not return the number of distinct keys in the multimap, which is given by keySet().size() or asMap().size(). 注意:此方法不会返回multimap中不同键的数量,该数量由keySet()。size()或asMap()。size()给出。 See the opening section of the Multimap class documentation for clarification. 有关说明,请参见Multimap类文档的开头部分。

If you want to get the number of distinct keys, try 如果要获取不同键的数量,请尝试

myMultimap.keySet().size()

size() 定义为数字键值 ,在您的情况下为4。

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

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