📜  如何在Java遍历 HashTable?

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

如何在Java遍历 HashTable?

HashTable 是一种底层数据结构,不保留 HashTable 中的插入顺序,它基于键的哈希码。不允许重复键,但可以重复值。键和值都允许使用异构对象。键和值都不允许使用 null 值,否则我们会得到 RunTimeException 说 NullPointerException。它实现了可序列化和可克隆的接口,但不实现 RandomAccess。其中的每个方法都是同步的,因此 HashTable 对象是线程安全的。如果我们的频繁操作是搜索操作,HashTable 是最好的选择。

方法:

我们可以通过多种方式遍历 HashTable,如下所示:

  1. 使用枚举接口
  2. 使用 Map 和 Enhance for 循环的 keySet() 方法
  3. 使用 Map 和 Iterator Interface 的 keySet() 方法
  4. 使用 Map 的 entrySet() 方法和增强的 for 循环
  5. 使用 Map 和 Iterator 接口的 entrySet() 方法
  6. 使用Java 8 版本中的 Iterable.forEach() 方法

现在让我们一一详细讨论所有方法的内部实现,以得到一个 通过HashTable更好地理解迭代

方法一:使用枚举接口



Java.util.Enumeration接口是预定义接口之一,其对象用于从集合框架变量中检索数据。仅在向前的方向上而不是在向后的方向上。此接口已被迭代器取代。

Java
// Java Program to Iterate through HashTable
// using enumeration interface
 
// Importing required packages
import java.util.*;
import java.util.Enumeration;
 
// MAin Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object where key is of Integer
        // type and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Ram");
        ht.put(2, "Shyam");
        ht.put(3, "Bijay");
        ht.put(4, "Hritik");
        ht.put(5, "Piyush");
 
        // Creating  Enumeration interface
        // and get keys() from Hashtable
        Enumeration e = ht.keys();
 
        // Iterating through the Hashtable
        // object
 
        // Checking for next element in Hashtable object
        // with the help of hasMoreElements() method
        while (e.hasMoreElements()) {
 
            // Getting the key of a particular entry
            int key = e.nextElement();
 
            // Print and display the Rank and Name
            System.out.println("Rank : " + key
                               + "\t\t Name : "
                               + ht.get(key));
        }
    }
}


Java
// Java program to iterate through HashTable
// using keySet method and enhance for-loop
 
// Importing required packages
import java.util.*;
import java.util.Set;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating Hashtable object in where key is of
        // Integer type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // custom entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Getting keySets of Hashtable and
        // storing it into Set
        Set setOfKeys = ht.keySet();
 
        // Iterating through the Hahstable
        // object using for-Each loop
        for (Integer key : setOfKeys) {
            // Print and display the Rank and Name
            System.out.println("Rank : " + key
                               + "\t\t Name : "
                               + ht.get(key));
        }
    }
}


Java
// Java program to iterate through HashTable
// using keySet method and Iterator Interface
 
// Importing required libraries
import java.util.*;
import java.util.Iterator;
import java.util.Set;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating Hashtale object where key is of Integer
        // type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Getting keySets of Hashtable and
        // storing it into Set
        Set setOfKeys = ht.keySet();
 
        // Creating an Iterator object to
        // iterate over the given Hashtable
        Iterator itr = setOfKeys.iterator();
 
        // Iterating through the Hahstable object
        // Checking for next element using hasNext() method
        while (itr.hasNext()) {
 
            // Getting key of a particular entry
            int key = itr.next();
 
            // Print and display the Rank and Name
            System.out.println("Rank : " + key
                               + "\t\t Name : "
                               + ht.get(key));
        }
    }
}


Java
// Java program to iterate through HashTable
// using entrySet method and enhance for-loop
 
// Importing required libraries
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object where key is of Integer
        // type and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Storing all entries of Hashtable
        // in a Set using entrySet() method
        Set > entrySet
            = ht.entrySet();
 
        // Iterating through the Hashtable object
        // using for-each loop
        for (Entry entry : entrySet) {
 
            // print ad display the Rank and Name
            System.out.println("Rank : " + entry.getKey()
                               + "\t\t Name : "
                               + entry.getValue());
        }
    }
}


Java
// Java program to iterate through hashtable using
// entrySet method and Iterator interface
 
// Importing required libraries
import java.util.*;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object where key is of Integer
        // type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to Hashtable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Storing all entries of Hashtable in a Set
        // using entrySet() method
        Set > entrySet
            = ht.entrySet();
 
        // Creating an Iterator object to
        // iterate over the given Hashtable
        Iterator > itr
            = entrySet.iterator();
 
        // Iterating through the Hashtable object
        // using iterator
 
        // Checking for next element
        // using hasNext() method
        while (itr.hasNext()) {
 
            // Getting a particular entry of HashTable
            Entry entry = itr.next();
 
            // Print and display the Rank and Name
            System.out.println("Rank : " + entry.getKey()
                               + "\t\t Name : "
                               + entry.getValue());
        }
    }
}


Java
// Java program to iterate through HashTable
// using Iterable forEach()method of java 8
 
// Import required libraries
import java.util.*;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object in where key is of
        // Integer type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Ruby");
        ht.put(5, "R");
 
        // Iterating through Hashtable using
        // forEach loop of java 8
        ht.forEach((key, value)
                       -> System.out.println(
                           "Rank : " + key
                           + "\t\t Name : " + value));
    }
}


输出
Rank : 5         Name : Piyush
Rank : 4         Name : Hritik
Rank : 3         Name : Bijay
Rank : 2         Name : Shyam
Rank : 1         Name : Ram

方法二:使用 Map 和 Enhance for 循环的 keySet() 方法

在Java中.util.HashMap.keySet()方法用于创建一组出的关键元件的Java的包含在哈希映射。它基本上返回键的集合视图,或者我们可以创建一个新集合并将键元素存储在其中。

Java

// Java program to iterate through HashTable
// using keySet method and enhance for-loop
 
// Importing required packages
import java.util.*;
import java.util.Set;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating Hashtable object in where key is of
        // Integer type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // custom entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Getting keySets of Hashtable and
        // storing it into Set
        Set setOfKeys = ht.keySet();
 
        // Iterating through the Hahstable
        // object using for-Each loop
        for (Integer key : setOfKeys) {
            // Print and display the Rank and Name
            System.out.println("Rank : " + key
                               + "\t\t Name : "
                               + ht.get(key));
        }
    }
}
输出
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java

方法三:使用 MapIterator Interface 的keySet() 方法

同样,我们将使用与上面示例中实现的方法相同的方法,但在这里进行迭代,我们将使用 Iterable 接口

Java

// Java program to iterate through HashTable
// using keySet method and Iterator Interface
 
// Importing required libraries
import java.util.*;
import java.util.Iterator;
import java.util.Set;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Creating Hashtale object where key is of Integer
        // type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Getting keySets of Hashtable and
        // storing it into Set
        Set setOfKeys = ht.keySet();
 
        // Creating an Iterator object to
        // iterate over the given Hashtable
        Iterator itr = setOfKeys.iterator();
 
        // Iterating through the Hahstable object
        // Checking for next element using hasNext() method
        while (itr.hasNext()) {
 
            // Getting key of a particular entry
            int key = itr.next();
 
            // Print and display the Rank and Name
            System.out.println("Rank : " + key
                               + "\t\t Name : "
                               + ht.get(key));
        }
    }
}
输出

Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java

方法四:使用Map的entrySet()方法增强的for循环

在Java中.util.HashMap.entrySet()方法用于创建一组出的相同元件的Java的包含在哈希映射。它基本上返回哈希映射的集合视图,或者我们可以创建一个新集合并将映射元素存储到其中。

Java

// Java program to iterate through HashTable
// using entrySet method and enhance for-loop
 
// Importing required libraries
import java.util.*;
import java.util.Map.Entry;
import java.util.Set;
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object where key is of Integer
        // type and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Storing all entries of Hashtable
        // in a Set using entrySet() method
        Set > entrySet
            = ht.entrySet();
 
        // Iterating through the Hashtable object
        // using for-each loop
        for (Entry entry : entrySet) {
 
            // print ad display the Rank and Name
            System.out.println("Rank : " + entry.getKey()
                               + "\t\t Name : "
                               + entry.getValue());
        }
    }
}
输出
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java

方法五:使用MapIterator接口的entrySet()方法

同样,我们将使用与上面示例中实现的方法相同的方法,但在这里进行迭代,我们将使用 Iterable 接口

Java

// Java program to iterate through hashtable using
// entrySet method and Iterator interface
 
// Importing required libraries
import java.util.*;
import java.util.Iterator;
import java.util.Map.Entry;
import java.util.Set;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object where key is of Integer
        // type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to Hashtable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Pearl");
        ht.put(5, "R");
 
        // Storing all entries of Hashtable in a Set
        // using entrySet() method
        Set > entrySet
            = ht.entrySet();
 
        // Creating an Iterator object to
        // iterate over the given Hashtable
        Iterator > itr
            = entrySet.iterator();
 
        // Iterating through the Hashtable object
        // using iterator
 
        // Checking for next element
        // using hasNext() method
        while (itr.hasNext()) {
 
            // Getting a particular entry of HashTable
            Entry entry = itr.next();
 
            // Print and display the Rank and Name
            System.out.println("Rank : " + entry.getKey()
                               + "\t\t Name : "
                               + entry.getValue());
        }
    }
}
输出
Rank : 5         Name : R
Rank : 4         Name : Pearl
Rank : 3         Name : Python
Rank : 2         Name : Scala
Rank : 1         Name : Java

6. 使用Java 8 中的Iterable.forEach() 方法

随着版本 8 中新特性的出现, Java 8 发布已经有一段时间了。随着该版本的发布,他们改进了一些现有的 API 并添加了一些新功能。其中之一是Java.lang.Iterable接口中的forEach() 方法

Java

// Java program to iterate through HashTable
// using Iterable forEach()method of java 8
 
// Import required libraries
import java.util.*;
 
// Main Class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating Hashtable object in where key is of
        // Integer type
        // and value is of String type
        Hashtable ht = new Hashtable<>();
 
        // Putting key-value pairs to HashTable object
        // Custom input entries
        ht.put(1, "Java");
        ht.put(2, "Scala");
        ht.put(3, "Python");
        ht.put(4, "Ruby");
        ht.put(5, "R");
 
        // Iterating through Hashtable using
        // forEach loop of java 8
        ht.forEach((key, value)
                       -> System.out.println(
                           "Rank : " + key
                           + "\t\t Name : " + value));
    }
}
输出
Rank : 1         Name : Java
Rank : 2         Name : Scala
Rank : 3         Name : Python
Rank : 4         Name : Ruby
Rank : 5         Name : R