entrySet()
方法的语法是:
hashmap.entrySet()
这里,
hashmap 是
HashMap
类的对象。
entrySet() 参数
entrySet()
方法不带任何参数。
entrySet() 返回值
返回哈希图所有条目的集合视图
注意: 集合视图意味着哈希图的所有条目都被视为一个集合。条目不会转换为集合。
示例 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()
方法返回哈希图中所有条目的集合视图。
entrySet()
方法可与 for-each 循环 一起使用以遍历哈希图的每个条目。
示例 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.Entry
是
Map
接口的嵌套类。注意这一行,
Entry<String, Integer> entry : numbers.entrySet()
这里,
entrySet()
方法返回一个所有条目的集合视图。
Entry
类允许我们存储和打印视图中的每个条目。