Monday, 14 April 2014

values : Get all Values from the Map

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

import java.util.*;
class MapValues{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to the Map */
  mapEx.put(1, "First");
  mapEx.put(2, "Second");
  mapEx.put(3, "Third");
  mapEx.put(4, "Fourth");
  
  System.out.println("Elements in the map are ");
  System.out.println(mapEx);
  
  /*Get the values from the map */
  Collection<String> values = mapEx.values();
  
  System.out.println("\nvalues in the map are");
  System.out.println(values);
  }
}


Output
Elements in the map are
{1=First, 2=Second, 3=Third, 4=Fourth}

values in the map are
[First, Second, Third, Fourth]

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 MapValuesEx{
  public static void main(String args[]){
         Map<Integer, String> mapEx = new TreeMap<> ();
  
  /* Add Data to the Map */
  mapEx.put(1, "First");
  mapEx.put(2, "Second");
  mapEx.put(3, "Third");
  mapEx.put(4, "Fourth");
  
  System.out.println("Elements in the map are ");
  System.out.println(mapEx);
  
  /*Get the values from the map */
   Collection<String> values = mapEx.values();
  
  System.out.println("\nvalues in the map are");
  System.out.println(values);
  
  System.out.println("\nAdding Data to the map");
  
  mapEx.put(5, "Five");
  mapEx.put(6, "Six");
  mapEx.put(7, "Seven");
  mapEx.put(8, "Eight");
  
  System.out.println("\nElements in the map are ");
  System.out.println(mapEx);
  
  System.out.println("\nvalues in the map are");
  System.out.println(values);
  
  System.out.println("\nRemoving values First,Second from Map");
  
  /* Removing values from Set */
  values.remove("First");
  values.remove("Second");  
  
  System.out.println("\nElements in the map are ");
  System.out.println(mapEx);
  
  System.out.println("\nvalues in the map are");
  System.out.println(values);
  }
}

Output
Elements in the map are
{1=First, 2=Second, 3=Third, 4=Fourth}

values in the map are
[First, Second, Third, Fourth]

Adding Data to the map

Elements in the map are
{1=First, 2=Second, 3=Third, 4=Fourth, 5=Five, 6=Six, 7=Seven, 8=Eight}

values in the map are
[First, Second, Third, Fourth, Five, Six, Seven, Eight]

Removing values First,Second from Map

Elements in the map are
{3=Third, 4=Fourth, 5=Five, 6=Six, 7=Seven, 8=Eight}

values in the map are
[Third, Fourth, Five, Six, Seven, Eight]









Prevoius                                                 Next                                                 Home

No comments:

Post a Comment