Java HashMap entrySet()

entrySet() 方法的语法是:

hashmap.entrySet()

这里,hashmapHashMap 类的一个 对象


entrySet() 参数

entrySet() 方法不接受任何参数。


entrySet() 返回值

  • 返回一个包含 HashMap 中所有条目的**视图集**。

注意:视图集意味着 HashMap 的所有条目都被视为一个集合。条目不会转换为一个集合。


示例 1:Java HashMap entrySet()

import java.util.HashMap;

class Main {
  public static void main(String[] args) {
    // create an HashMap
    HashMap<String, Integer> prices = new HashMap<>();

    // insert entries to the HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("HashMap: " + prices);

    // return set view of mappings
    System.out.println("Set View: " + prices.entrySet());
  }
}

输出

HashMap: {Pant=150, Bag=300, Shoes=200}
Set View: [Pant=150, Bag=300, Shoes=200]

在上面的示例中,我们创建了一个名为 prices 的哈希表。请注意表达式:

prices.entrySet()

在此,entrySet() 方法返回 HashMap 中所有条目的视图集。

entrySet() 方法可以与 for-each 循环一起使用,以遍历 HashMap 中的每个条目。

示例 2:for-each 循环中的 entrySet() 方法

import java.util.HashMap;
import java.util.Map.Entry;

class Main {
    public static void main(String[] args) {

        // Creating a HashMap
        HashMap<String, Integer> numbers = new HashMap<>();
        numbers.put("One", 1);
        numbers.put("Two", 2);
        numbers.put("Three", 3);
        System.out.println("HashMap: " + numbers);

        // access each entry of the hashmap
        System.out.print("Entries: ");

        // entrySet() returns a set view of all entries
        // for-each loop access each entry from the view
        for(Entry<String, Integer> entry: numbers.entrySet()) {
            System.out.print(entry);
            System.out.print(", ");
        }
    }
}

输出

HashMap: {One=1, Two=2, Three=3}
Entries: One=1, Two=2, Three=3, 

在上面的示例中,我们导入了 java.util.Map.Entry 包。Map.EntryMap 接口的嵌套类。请注意这行代码:

Entry<String, Integer> entry :  numbers.entrySet()

在此,entrySet() 方法返回一个**所有条目的视图集**。Entry 类允许我们存储和打印视图中的每个条目。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战