English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Java HashMap entrySet()返回哈希映射中存在的所有映射(条目)的集合视图。
entrySet()方法的语法为:
hashmap.entrySet()
entrySet()方法不带任何参数。
返回哈希映射所有条目的集合视图
注意:set视图意味着hashmap的所有条目都被视为一个集合。条目不转换为集合。
import java.util.HashMap; class Main { public static void main(String[] args) { // Créer un HashMap HashMapprices = new HashMap<>(); // 向HashMap插入条目 prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("HashMap: "); + prices); //返回映射的集合视图 System.out.println("Set 视图: " + prices.entrySet()); } }
Output result
HashMap: {Pant=150, Bag=300, Shoes=200} Vue Set: [Pant=150, Bag=300, Shoes=200]
Dans l'exemple ci-dessus, nous avons créé une carte de hachage nommée prices. Notez l'expression
prices.entrySet()
Dans ce cas, la méthode entrySet() renvoie une vue de collection de toutes les entrées de la carte de hachage.
La méthode entrySet() peut être utilisée avecfor-Boucle eachutilisé ensemble pour itérer sur chaque entrée de la carte de hachage.
import java.util.HashMap; import java.util.Map.Entry; class Main { public static void main(String[] args) { // Créer un HashMap HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("One", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: "); + numbers); //Accéder à chaque entrée de la hashmap System.out.print("Entries: "); //entrySet() renvoie une vue de collection de toutes les entrées //for-Each boucle itère sur chaque entrée de la vue for(Entry<String, Integer> entry: numbers.entrySet()) { System.out.print(entry); System.out.print(", "); } } }
Output result
HashMap: {One=1, Two=2, Three=3} Entries: One=1, Two=2, Three=3,
In the above example, we imported the java.util.Map.Entry package. Map.Entry is a nested class of the Map interface. Note this line,
Entry<String, Integer> entry : numbers.entrySet()
Here, the entrySet() method returns a view of the collection of all entries. The Entry class allows us to store and print each entry in the view.
Related reading
HashMap keySet() - Return a view of the set of all keys
HashMap values() - Return a view of the collection of all values