Collections – Map Interface

Hi everyone! Today i’m going to explain about Map Interface in Java. We started the these article series with Collections and Map Interface is a valuable part of that Collection Framework. But Map interface is not a subtype Collection Interface. It behaves little bit different.
Map stores elements key-value pairs. You can access to values with key. It can not contains duplicate keys. Each key has only one value. Some of Map implementations can allow null value(key or value) but some of not. Example, HashMap and LinkedHashMap allow that but TreeMap doesn’t allow.

Lets take a look Map interface methods in shortly.

public Object put(Object key, Object value) : This method is used to insert an entry in this map
public void putAll(Map map) : This method is used to insert a map in this map.
public Object remove(Object key) : This method is used to remove an entry for key
public Object get(Object key)  : This method is used to get value for key
public boolean containsKey(Object key) : This method is used to check key is exists.
public Set keySet() : This method returns containing all keys
public Set entrySet() : This method returns containing all keys and values.

Here is the example of code about Map Interface.

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

public class Main {

    public static void main(String... args) {
        Map<String, Integer> nameAgeMap = new HashMap<>();
        // Adding elements to map
        nameAgeMap.put("Ufuk", 26);
        nameAgeMap.put("Halis", 26);
        nameAgeMap.put("Alice", 30);

        write(nameAgeMap);
        System.out.println("------------------------------------");
        //Removing element from map
        nameAgeMap.remove("Ufuk");
        write(nameAgeMap);
        System.out.println("Map contains key Ufuk : " + nameAgeMap.containsKey("Ufuk"));
    }

    private static void write(Map map) {
        Set<Map.Entry> entries = map.entrySet();
        for (Map.Entry entry : entries) {
            System.out.println("Key : " + entry.getKey());
            System.out.println("Value : " + entry.getValue());
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s