Wednesday 4 June 2014

HashMap : values : Get All the Values in the Map

public Collection<V> values()
Returns a Collection view of the values contained in this map.

import java.util.*;

class HashMapValues{
 public static void main(String args[]){
  HashMap<Integer, String> myMap;
  Collection<String> myCollection;
  
  myMap = new HashMap<> ();
  
  /* Add Data to myMap */
  myMap.put(100, "Hi");
  myMap.put(25, "How");
  myMap.put(31, "Are");

  myCollection = myMap.values();
  
  System.out.println("Values in myMap are");
  System.out.println(myCollection);  
 }
}

Output
Values in myMap are
[Hi, How, Are]

1. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa.
import java.util.*;

class HashMapValues1{
 public static void main(String args[]){
  HashMap<Integer, String> myMap;
  Collection<String> myCollection;
  
  myMap = new HashMap<> ();
  
  /* Add Data to myMap */
  myMap.put(100, "Hi");
  myMap.put(25, "How");
  myMap.put(31, "Are");

  myCollection = myMap.values();
  
  System.out.println("Elements in myMap are");
  System.out.println(myMap);
  System.out.println("Values in myMap are");
  System.out.println(myCollection);

  System.out.println("\nRemoving the value \"How\" from myCollection");
  myCollection.remove("How");
  
  System.out.println("\nElements in myMap are");
  System.out.println(myMap);
  System.out.println("Values in myMap are");
  System.out.println(myCollection);
  
  System.out.println("\nAdding Key 99 to myMap");
  myMap.put(99, "wxyz");
  
  System.out.println("\nElements in myMap are");
  System.out.println(myMap);
  System.out.println("Values in myMap are");
  System.out.println(myCollection);  
 }
}

Output
Elements in myMap are
{100=Hi, 25=How, 31=Are}
Values in myMap are
[Hi, How, Are]

Removing the value "How" from myCollection

Elements in myMap are
{100=Hi, 31=Are}
Values in myMap are
[Hi, Are]

Adding Key 99 to myMap

Elements in myMap are
{99=wxyz, 100=Hi, 31=Are}
Values in myMap are
[wxyz, Hi, Are]



Prevoius                                                 Next                                                 Home

No comments:

Post a Comment