Hashtable
Get Collection view of Hashtable values example
With this example we are going to demonstrate how to get a Collection view of the Hashtable values. In short, to get a Collection view of the Hashtable values you should:
- Create a new Hashtable.
- Populate the hashtable with elements, using
put(K key, V value)
API method of Hashtable. - Invoke
values()
API method of Hashtable. It returns a Collection that contains all the values in the Hashtable. The collection is backed by the Hashtable, meaning that elements removed from the Collection will also be removed from the originating Hashtable. - Note that it is not permitted to add an element to the resultant value set and an UnsupportedOperationException will be thrown in case we try to.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; import java.util.Hashtable; import java.util.Collection; public class HashtableValuesCollection { public static void main(String[] args) { // Create a Hashtable and populate it with elements Hashtable hashtable = new Hashtable(); hashtable.put("key_1","value_1"); hashtable.put("key_2","value_2"); hashtable.put("key_3","value_3"); hashtable.put("key_4","value_4"); hashtable.put("key_5","value_5"); /* Collection values() operation returns a Collection containing all values in Hashtable. The values collection is backed by the Hashtable thus elements removed from the Collection will also be removed from the originating Hashtable. Nevertheless it is not permitted to add an element to the resultant value set and java.lang.UnsupportedOperationException exception will be thrown in case we try to. */ Collection valuesCollection = hashtable.values(); System.out.println("valuesCollection contains : " + valuesCollection); valuesCollection.remove("value_2"); System.out.println("after removing value_2 from valuesCollection, valuesCollection contains : " + valuesCollection + " Hashtable contains : " + hashtable); } }
Output:
valuesCollection contains : [value_5, value_4, value_3, value_2, value_1]
after removing value_2 from valuesCollection, valuesCollection contains : [value_5, value_4, value_3, value_1] Hashtable contains : {key_5=value_5, key_4=value_4, key_3=value_3, key_1=value_1}
This was an example of how to get a Collection view of the Hashtable values in Java.