获取 Java 中 HashMap 中的元素数量


使用 size() 方法获取元素数量。

首先让我们创建一个 HashMap 并添加元素 −

HashMap hm = new HashMap();
// Put elements to the map
hm.put("Maths", new Integer(98));
hm.put("Science", new Integer(90));
hm.put("English", new Integer(97));

现在,获取大小 −

hm.size()

以下是获取 HashMap 元素数量的示例 −

示例

 实时演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create a hash map
      HashMap hm = new HashMap();
      // Put elements to the map
      hm.put("Maths", new Integer(98));
      hm.put("Science", new Integer(90));
      hm.put("English", new Integer(97));
      hm.put("Physics", new Integer(91));
      hm.put("Chemistry", new Integer(93));
      // Get a set of the entries
      Set set = hm.entrySet();
      // Get an iterator
      Iterator i = set.iterator();
      // Display elements
      while(i.hasNext()) {
         Map.Entry me = (Map.Entry)i.next();
         System.out.print(me.getKey() + ": ");
         System.out.println(me.getValue());
      }
      System.out.println();
      System.out.println("Count of elements = "+hm.size());
   }
}

输出

Maths: 98
English: 97
Chemistry: 93
Science: 90
Physics: 91
Size: 5

更新时间:2019 年 7 月 30 日

13K+ 浏览次数

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.