Tuesday, November 19, 2024
Google search engine
HomeLanguagesJavaMap Values() Method in Java With Examples

Map Values() Method in Java With Examples

Map Values() method returns the Collection view of the values contained in this map. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. 

Syntax:

map.values()

Parameter: This method does not take any parameter.

Return value: It returns a collection view of all the values present in the map.

Example 1:

Java




// Java program to illustrate the
// use of Map.Values() Method
import java.util.*;
  
public class GfG {
  
      // Main Method
    public static void main(String[] args)
    {
        // Initializing a Map of type HashMap 
        Map<Integer, String> map
            = new HashMap<Integer, String>();
  
        map.put(12345, "student 1");
        map.put(22345, "student 2");
        map.put(323456, "student 3");
        map.put(32496, "student 4");
        map.put(32446, "student 5");
        map.put(32456, "student 6");
  
        System.out.println(map.values());
    }
}


 

Output:

[student 4, student 3, student 6, student 1, student 2, student 5]

As you can see, the output of the above example is returning a collection view of values. So any change in the map will be reflected in the collection view automatically. So always take the generic of collection same as the generic of the values of the map otherwise it will give an error.

Example 2:

Java




// Java program to illustrate the
// use of Map.Values() Method
import java.util.*;
  
public class GfG {
  
      // Main Method
    public static void main(String[] args)
    {
        // Initializing a Map of type HashMap 
        Map<Integer, String> map
            = new HashMap<Integer, String>();
  
        map.put(12345, "student 1");
        map.put(22345, "student 2");
        map.put(323456, "student 3");
        map.put(32496, "student 4");
        map.put(32446, "student 5");
        map.put(32456, "student 6");
        Collection<String> collectionValues = map.values();
          
          
        System.out.println("<------OutPut before modification------>\n");
        for(String s: collectionValues){
            System.out.println(s);
        }
         
        map.put(3245596, "student 7");
        System.out.println("\n<------OutPut after modification------>\n");
        for(String s: collectionValues){
            System.out.println(s);
        }
    }
}


Output:

<------OutPut before modification------>

student 4
student 3
student 6
student 1
student 2
student 5

<------OutPut after modification------>

student 4
student 3
student 6
student 1
student 2
student 7
student 5

RELATED ARTICLES

Most Popular

Recent Comments