Get All Values of Hashtable in Java Example

This example shows how to get all values stored in the Hashtable in Java. This example also shows how to get all Hashtable values using the elements method and values method.

How to get all the values of Hashtable in Java?

There are a couple of ways using which we can get all the values stored in the hashtable object.

1. Using the elements method

The Hashtable elements method returns an Enumeration over the hashtable values.

Once we get the enumeration, we can iterate through all the values of the hash table using the hasMoreElements and nextElement methods as given below.

Output

2. Using the values method

The Hashtable values method returns a Collection view of all the values contained in the hashtable object.

The Collection object is a view that is backed by the original hashtable object. That means any changes you make to this view will also be reflected in the original hashtable object, and vice versa.

We can get an iterator over values using the iterator method of the Collections. Once we get an iterator, we can iterate through the values using the hasNext and next methods as given below.

Output

The elements vs values method

  • The elements method returns an Enumeration while the values method returns a Collection view.
  • We can directly iterate over elements using the Enumeration while we need to get the iterator from Collection object to iterate through elements
  • The elements method is inherited from the JDK 1.0 Dictionary class while the values method was introduced in Java 2.0 when the Hashtable class implemented the Map interface.
  • We can remove the elements while iterating using the iterator which cannot be done using the Enumeration.

This example is a part of the Hashtable in Java Tutorial with Examples.

Please let me know your views in the comments section below.

References:
Java 8 Hashtable Documentation

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

Add Comment

Your email address will not be published. Required fields are marked *

Online Shopping