📜  如何在Java中迭代 HashMap?

📅  最后修改于: 2022-05-13 01:55:35.787000             🧑  作者: Mango

如何在Java中迭代 HashMap?

HashMap 是 Java 集合的一部分,通过将数据存储在 (Key, Value) 对中以通过另一种类型的索引访问它们,提供了Java Map 接口的基本实现。一个对象被列为另一个对象(值)的键(索引)。如果您尝试插入重复键,它将替换相应键的元素。为了使用这个类及其方法,需要导入Java.util.HashMap包或其超类。

有多种方法可以迭代 HashMap,其中 5 种如下所列:

  1. 使用迭代器遍历 HashMap EntrySet。
  2. 使用 Iterator 遍历 HashMap KeySet。
  3. 使用 for-each 循环迭代 HashMap。
  4. 使用 Lambda 表达式遍历 HashMap。
  5. 使用 Stream API 循环遍历 HashMap。

方法一:使用for循环遍历HashMap。通过 for 循环迭代 HashMap 以使用getValue()getKey()函数。

实现:在下面给出的代码中,entrySet() 用于返回映射元素的集合视图。从下面给出的代码:

  • set.getValue() 从集合中获取值。
  • set.getKey() 从集合中获取密钥。
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 foodTable
            = new HashMap();
 
        // 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 set :
             foodTable.entrySet()) {
 
            // Printing all elements of a Map
            System.out.println(set.getKey() + " = "
                               + set.getValue());
        }
    }
}


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 charType
            = new HashMap();
 
        // 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));
    }
}


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 intType
            = new HashMap();
 
        // 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 > new_Iterator
            = intType.entrySet().iterator();
 
        // Iterating every set of entry in the HashMap
        while (new_Iterator.hasNext()) {
            Map.Entry new_Map
                = (Map.Entry)
                      new_Iterator.next();
 
            // Displaying HashMap
            System.out.println(new_Map.getKey() + " = "
                               + new_Map.getValue());
        }
    }
}


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 charType
            = new HashMap();
 
        // 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));
    }
}


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 intType
            = new HashMap();
 
        // 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()));
    }
}


输出
P = Python
A = Angular
H = Hibernate
J = Java

方法二:使用forEach遍历HashMap。在第二种方法中,forEach函数迭代键值对。

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 charType
            = new HashMap();
 
        // 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));
    }
}
输出
P = Python
A = Angular
H = Hibernate
J = Java

方法三:使用迭代器遍历HashMap。在这个方法中,迭代器被用来迭代HashMap中的每个映射对,如下面的Java程序所示。

例子:

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 intType
            = new HashMap();
 
        // 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 > new_Iterator
            = intType.entrySet().iterator();
 
        // Iterating every set of entry in the HashMap
        while (new_Iterator.hasNext()) {
            Map.Entry new_Map
                = (Map.Entry)
                      new_Iterator.next();
 
            // Displaying HashMap
            System.out.println(new_Map.getKey() + " = "
                               + new_Map.getValue());
        }
    }
}


输出
1 = First
2 = Second
3 = Third
4 = Fourth

方法 4:使用 Lambda 表达式遍历 HashMap

lambda 表达式是一小段代码,它接受参数并返回一个值。 Lambda 表达式类似于方法,但它们不需要名称,并且可以直接在方法体中实现。最简单的 lambda 表达式包含一个参数和一个表达式:

parameter -> expression

例子:

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 charType
            = new HashMap();
 
        // 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));
    }
}
输出
A = Apple
B = Basketball
C = Cat
D = Dog

方法 5:使用 Stream API 循环遍历 HashMap

下面的示例在流 API 的帮助下迭代 HashMap。

Stream API 用于处理对象集合。

Streams 不改变原始数据结构,它们只根据流水线方法提供结果

脚步 :

  • 首先调用entrySet().stream()方法,该方法又返回 Stream 对象。
  • 接下来是forEach 方法,它迭代 entrySet() 中的输入对象。请参阅下面的代码。

例子:

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 intType
            = new HashMap();
 
        // 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()));
    }
}
输出
1 : First
2 : Second
3 : Third
4 : Fourth