Retrieve all Hashtable values in Java
This example shows how to get all the elements of the Hashtable in a collection of values Collection belonging to Hashtable using the values() of the Hashtable.This code retrieves the value collection from Hashtable.
import java.util.Enumeration;Runtime:
import java.util.Iterator;
import java.util.Hashtable;
import java.util.Collection;
public class Recovery {
public static void main(String[] args) {
//create a Hashtable
Hashtable ht = new Hashtable();
//add keys and values
ht.put("1","one");
ht.put("2","two");
ht.put("3","three");
/*
retrieve all values using
the values()
method */
Collection c = ht.values();
System.out.println("The values in the Hashtable collection are: ");
//iterate through the collection
Iterator itr = c.iterator();
while(itr.hasNext())
System.out.println(itr.next());
/*
the resulting collection is a HashTable
If a value is removed from the collection, it will also be removed
from the original Hashtable collection. This does not imply adding an element
*/
//removing one from the Hashtable
c.remove("One");
//display all values of Hashtable
System.out.println("Hashtable after deleting an item");
Enumeration e = ht.elements();
while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}
The values in the Hashtable collection are:
three
two
one
Hashtable after deleting an element
three
two
one