Different Collection views provided Map interface

Different Collection views provided Map interface

Answer: Map is object which maps keys to its values. Map can’t contain duplicate keys. Each key will map to one value. Map interface includes methods which can be used for general operations i.e.get, put, containsKey, containsValue, remove, size, and empty for bulk operations i.e. putAll and clear.

It provides three collection views methods which allow Map to be viewed as Collection in below ways:

  • Keyset: This method provides Set of the keys contained in Map.
  • entrySet: This method provides Collection of values contained in Map. Please note basically this Collection is not Set because we can have multiple keys that is map to same value.
  • Values: This method provides Set of key value pairs contained in Map. Map interface provides small nested interface that is called Map.Entry and type of the elements in this Set.

Please see java example below:

package com.javahonk.mapviews;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class MapCollectionsViewsTest {

    public static void main(String[] args) {

    Map<String, String> map = new HashMap<String, String>();

    map.put("Java", "Java");
    map.put("Honk", "Honk");
    map.put("Test", "Test");
    //keySet example
    System.out.println("keySet() example:\n");
    Set<String> set = map.keySet();
    for (String string : set) {
        System.out.println("Key: "+string+" Value: "
    //entrySet example
    System.out.println("\nentrySet() example:\n");  
    Set<Entry<String, String>> set2 = map.entrySet();
    for (Entry<String, String> entry : set2) {
        System.out.println("Key: "+entry.getKey()+" Value: "
    //values example
    System.out.println("\nvalues() example:\n");




Different Collection views provided Map interface

Leave a Reply

Your email address will not be published. Required fields are marked *

I am not Robot *