Java 程序以检索 HashMap 中的所有键的集合


首先,创建一个 HashMap 并添加元素

HashMap hm = new HashMap();
hm.put("Wallet", new Integer(700));
hm.put("Belt", new Integer(600));
hm.put("Backpack", new Integer(1200));

现在,检索所有键

Set keys = hm.keySet();
System.out.println("
Keys..."); Iterator i = keys.iterator(); while (i.hasNext()) {    System.out.println(i.next()); }

以下是获取 HashMap 中所有键集合的示例

示例

 在线演示

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      // Create hash map
      HashMap hm = new HashMap();
      hm.put("Wallet", new Integer(700));
      hm.put("Belt", new Integer(600));
      hm.put("Backpack", new Integer(1200));
      System.out.println("Map = "+hm);
      Set keys = hm.keySet();
      System.out.println("
Keys..."); Iterator i = keys.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }

以下是输出

Map = {Backpack=1200, Belt=600, Wallet=700}
Keys...
Backpack
Belt
Wallet

更新于:30-Jul-2019

256 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.