【问题标题】:Get keys and values from Multimap从 Multimap 获取键和值
【发布时间】:2017-01-15 23:20:51
【问题描述】:

我想从 multiMap 中打印对象的所有键和所有属性。 同一个键可以有不同的对象。

我使用以下代码创建了 multiMap:

Multimap<Integer,Country> country=ArrayListMultimap.create();

我的班级国家是:

class Country {
    String country;
    int population;
}

如何从中检索所有对象属性: 使用 HashMap 我正在使用以下代码:

 for (Map.Entry p : country.entrySet()) {
    Country country=(Country)p.getValue();
    nameCountry=country.country;
    population=country.population;
 }

【问题讨论】:

    标签: java multimap


    【解决方案1】:

    使用 keySet() 来避免重复,如果你想要重复,使用 keys()。然后通过get(..)获取国家实例

    【讨论】:

    • 之前从未使用过Multimap,我见过一些字符串和整数的例子,但没有使用类对象。你有什么例子吗?
    • 作为值还是键?它与 map 几乎相同(为 key 对象调用 hashCode()),但如果重复出现,则不会删除现有的 key
    【解决方案2】:

    使用几乎相同,但不是entrySet(),而是使用entries()

     for (Map.Entry<Integer, Country> p : country.entries()) {
         Country country=(Country)p.getValue();
         nameCountry=country.country;
         population=country.population;
      }
    

    【讨论】:

      【解决方案3】:

      您可以使用 keySet 获取唯一键,然后获取该键的集合。

       for (Integer key : countries.keySet()) {
            Collection<Country> collection = countries.get(key);
            for (Country country : collection)
            {
              String name = country.country;
              int poplulation = country.population;
            }
        } 
      

      【讨论】:

        【解决方案4】:

        举个例子

        Multimap<String, String> NameList = ArrayListMultimap.create();
        
            NameList.put("david", "1");
            NameList.put("david", "2");
            NameList.put("jonathan", "4");
            NameList.put("david", "2");
        
            Collection<String> values = NameList.get("david");
            System.out.println("all david list: " + values);
        
            Iterator iterator = values.iterator();
            System.out.println("first element: " + iterator.next());
            System.out.println("second element: " + iterator.next());
            System.out.println("third element: " + iterator.next());
         System.out.println("number of david elements "+NameList.get("david").size());
        

        打印出来的结果是

        all david list: [1, 2, 2]
        first element: 1
        second element: 2
        third element: 2
        number of david elements 3
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-01-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多