w3resource

Java: Create a set view of the mappings contained in a map


9. Get Set View of Map Entries

Write a Java program to create a set view of the mappings contained in a map.

Sample Solution:-

Java Code:

import java.util.*;  
public class Example9 {  
    public static void main(String args[]) {
  HashMap < Integer, String > hash_map = new HashMap < Integer, String > ();
  hash_map.put(1, "Red");
  hash_map.put(2, "Green");
  hash_map.put(3, "Black");
  hash_map.put(4, "White");
  hash_map.put(5, "Blue");
  // create set view for the map
  Set set = hash_map.entrySet();
  // check set values
  System.out.println("Set values: " + set);
 }
}

Sample Output:

Set values: [1=Red, 2=Green, 3=Black, 4=White, 5=Blue]

For more Practice: Solve these Related Problems:

  • Write a Java program to create a set view of the entries in a HashMap using entrySet() and then print each mapping.
  • Write a Java program to iterate over a map’s entrySet() using Java streams and print the key-value pairs.
  • Write a Java program to convert a map’s entrySet() into a List and then sort the list by keys.
  • Write a Java program to create a set view of a map’s entries and filter them based on a condition using streams.

Go to:


PREV : Check If Value Exists in Map.
NEXT : Get Value by Key from Map.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.