首页 > 编程语言 >How to Iterate HashMap in Java?

How to Iterate HashMap in Java?

时间:2022-12-31 16:11:53浏览次数:86  
标签:Map java HashMap util How put Java

https://www.geeksforgeeks.org/how-to-iterate-hashmap-in-java/

 

HashMap is a part of Java’s collection providing the basic implementation of the Map interface of Java by storing the data in (Key, Value) pairs to access them by an index of another type. One object is listed as a key (index) to another object (value). If you try to insert the duplicate key, it will replace the element of the corresponding key. In order to use this class and its methods, it is necessary to import java.util.HashMap package or its superclass.

There is a numerous number of ways to iterate over HashMap of which 5 are listed as below: 

 
  1. Iterate through a HashMap EntrySet using Iterators.
  2. Iterate through HashMap KeySet using Iterator.
  3. Iterate HashMap using for-each loop.
  4. Iterating through a HashMap using Lambda Expressions.
  5. Loop through a HashMap using Stream API.

Method 1: Using a for loop to iterate through a HashMap. Iterating a HashMap through a for loop to use getValue() and getKey() functions.

Implementation: In the code given below, entrySet() is used to return a set view of mapped elements. From the code given below:

  <iframe data-google-container-id="1" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="1" id="google_ads_iframe_/27823234/GFG_Desktop_PostContent_336x280_0" marginheight="0" marginwidth="0" scrolling="no" src="https://5d76753d5d858e2042a28edf990fc295.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" title="3rd party ad content" width="1"></iframe>
  • set.getValue() to get value from the set.
  • set.getKey() to get key from the set.
  • Java
 
// Java Program to Iterate over HashMap   // Importing Map and HashMap classes // from package names java.util import java.util.HashMap; import java.util.Map;   // Class for iterating HashMap using for loop public class GFG {       // Main driver method     public static void main(String[] args)     {         // Creating a HashMap         Map<String, String> foodTable             = new HashMap<String, String>();           // Inserting elements to the adobe HashMap         // Elements- Key value pairs using put() method         foodTable.put("A", "Angular");         foodTable.put("J", "Java");         foodTable.put("P", "Python");         foodTable.put("H", "Hibernate");           // Iterating HashMap through for loop         for (Map.Entry<String, String> set :              foodTable.entrySet()) {               // Printing all elements of a Map             System.out.println(set.getKey() + " = "                                + set.getValue());         }     } }
Output
P = Python
A = Angular
H = Hibernate
J = Java

Method 2: Using a forEach to iterate through a HashMap. In the second method, the forEach function to iterate the key-value pairs.

  • Java
 
// Java Program to Iterate over HashMap // Iterating HashMap using forEach   // Importing Map and HashMap classes // from package names java.util import java.util.HashMap; import java.util.Map;   public class GFG {       // Main driver method     public static void main(String[] args)     {         // Creating hash map         Map<Character, String> charType             = new HashMap<Character, String>();           // Inserting data in the hash map.         charType.put('J', "Java");         charType.put('H', "Hibernate");         charType.put('P', "Python");         charType.put('A', "Angular");           // Iterating HashMap through forEach and         // Printing all. elements in a Map         charType.forEach(             (key, value)                 -> System.out.println(key + " = " + value));     } }
Output
P = Python
A = Angular
H = Hibernate
J = Java

Method 3: Using an iterator to iterate through a HashMap. In this method, iterator is being used to iterate each mapped pair in HashMap as shown in below java program.

Example:

  • Java
 
// Java Program to Iterate over HashMap // Using Iterator   // Importing classes from java.util package import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry;   public class GFG {       // Main driver method     public static void main(String[] arguments)     {         // Creating Hash map         Map<Integer, String> intType             = new HashMap<Integer, String>();           // Inserting data(Key-value pairs) in hashmap         intType.put(1, "First");         intType.put(2, "Second");         intType.put(3, "Third");         intType.put(4, "Fourth");           // Iterator         Iterator<Entry<Integer, String> > new_Iterator             = intType.entrySet().iterator();           // Iterating every set of entry in the HashMap         while (new_Iterator.hasNext()) {             Map.Entry<Integer, String> new_Map                 = (Map.Entry<Integer, String>)                       new_Iterator.next();               // Displaying HashMap             System.out.println(new_Map.getKey() + " = "                                + new_Map.getValue());         }     } }

 
 

Output
1 = First
2 = Second
3 = Third
4 = Fourth

 Method 4: Iterating through a HashMap using Lambda Expressions

A lambda expression is a short block of code that takes in parameters and returns a value.  Lambda expressions are similar to methods, but they do not need a name, and they can be implemented right in the body of a method. The simplest lambda expression contains a single parameter and an expression:

<iframe data-google-container-id="2" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="250" id="google_ads_iframe_/27823234/gfg_outstream_incontent_0" marginheight="0" marginwidth="0" scrolling="no" src="https://5d76753d5d858e2042a28edf990fc295.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" title="3rd party ad content" width="300"></iframe>
parameter -> expression

Example: 

  • Java
 
// Iterating HashMap using Lambda Expressions- forEach() // Importing Map and HashMap classes // from java.util package import java.util.HashMap; import java.util.Map;   // Class public class GFG {       // Main driver method     public static void main(String[] args)     {         // Creating hash map         Map<Character, String> charType             = new HashMap<Character, String>();           // Inserting elements(key-value pairs)         // in the hash map ( Custom inputs)         charType.put('A', "Apple");         charType.put('B', "Basketball");         charType.put('C', "Cat");         charType.put('D', "Dog");           // Iterating through forEach and         // printing the elements         charType.forEach(             (key, value)                 -> System.out.println(key + " = " + value));     } }
Output
A = Apple
B = Basketball
C = Cat
D = Dog

Method 5: Loop through a HashMap using Stream API

The below example iterates over a HashMap with the help of the stream API. 

Stream API is used to process collections of objects.

Streams don’t change the original data structure, they only provide the result as per the pipelined methods

 Steps :

  • First invoke entrySet().stream() method which inturn returns Stream object.
  • Next forEach method, which iterates the input objects that are in the entrySet(). See the below code.

Example:

  • Java
 
// Java Program to Iterate over HashMap // Loop through a HashMap using Stream API   // Importing classes from // package named 'java.util' import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry;   // HashMap class public class GFG {       // Main driver method     public static void main(String[] arguments)     {         // Creating hash map         Map<Integer, String> intType             = new HashMap<Integer, String>();           // Inserting data(key-value pairs) in HashMap         // Custom inputs         intType.put(1, "First");         intType.put(2, "Second");         intType.put(3, "Third");         intType.put(4, "Fourth");           // Iterating every set of entry in the HashMap, and         // printing all elements of it         intType.entrySet().stream().forEach(             input             -> System.out.println(input.getKey() + " : "                                   + input.getValue()));     } }
Output
1 : First
2 : Second
3 : Third
4 : Fourth

标签:Map,java,HashMap,util,How,put,Java
From: https://www.cnblogs.com/kungfupanda/p/17016863.html

相关文章

  • JAVA零基础小白上手教程day08-JAVAOOP面向对象
    day08-JAVAOOP课程目标1.【理解】什么是接口2.【掌握】接口的定义格式3.【掌握】接口的使用4.【理解】接口的成员特点5.【理解】类和接口抽象类和接口之间的关......
  • How to Maintain Insertion Order of the Elements in Java HashMap?
    https://www.geeksforgeeks.org/how-to-maintain-insertion-order-of-the-elements-in-java-hashmap/ Whenelementsgetfromthe HashMap duetohashingtheorder......
  • 生成JavaDoc文档
    javadoc在Dos命令中生成java文档打开.java所在文件目录目录上cmd\..\..javadoc-encodingUTF-8-charsetUTF-8Demo01.java生成index.html文件javadoc在IDEA生......
  • 第八章《Java高级语法》第8节:Java可变参数
    如果需要定义一个2个数相加的方法,可以在定义方法时为方法设置2个参数,同理,如果要定义一个3个数相加的方法,就给方法设置3个参数,但是如果想定义一个任意多数字相加的方法该怎么......
  • 第八章《Java高级语法》第11节:泛型
    ​泛型也JDK1.5引入的一种技术,它改变了核心API中的许多类和方法。使用泛型,可以建立类型安全模式来处理各种数据的类、接口和方法。使用泛型,一旦定义了一个算法,就可以独立于......
  • 第八章《Java高级语法》第12节:Lambda表达式
    ​Lambda表达式是JDK8的一个新特性,它可以定义大部分的匿名内部类,从而让程序员能写出更优雅的Java代码,尤其在集合的各种操作中可以极大地优化代码结构。8.12.1认识Lambda......
  • 音视频:JavaCV 视频切片(MPEG-TS)(HLS)
    需要进行简单的音视频编程,如果不是特别数据C/C++,那么JavaCV应该是比较好的选择,下面记录一下使用JavaCV视频切片(MPEG-TS)(HLS)的方法。注意:存放HLS切片的目录必须存在(不会自......
  • 第八章《Java高级语法》第7节:枚举
    ​枚举是JDK1.5中新增加的一种数据类型,它最大的特点就是枚举数据类型的取值范围由程序员自己规定,本小节将会讲解枚举的用法以及实现枚举的原理。8.7.1枚举的概念及定义方式......
  • day04_java基础
    day04_java基础课程目标1.【掌握】IDEA的基本使用2.【理解】什么是数组3.【掌握】数组的定义及初始化4.【理解】数组的内存图6.【理解】数组常见的问题7.......
  • JAVA零基础小白学习教程day05_java基础
    day05_java基础课程目标1.【理解】什么是方法2.【掌握】方法的语法,抄3遍3.【理解】方法的执行流程4.【掌握】方法的案例:常用类型5.【理解】方法的重载6.【......