Map element adding

In this chapter you will learn:

  1. How to add key value pair to a Map
  2. How to create a new map from an existing map

Add key value pair to a map

When adding entries to a Map we have to provide both key and value. In other words, we have to put value into a Map pair by pair.

import java.util.HashMap;
import java.util.Map;
//from j a va2s.c  o  m
public class Main {
  public static void main(String[] a) {

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println(map);
  }
}

Create map from another map

We can choose to add all key and value pairs from another map in one method call with putAll.

import java.util.HashMap;
import java.util.Map;
//from   j  av  a  2 s .  co  m
public class Main {
  public static void main(String[] a) {
    Map<String,String> map = new HashMap<String,String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");
    map.put(null, null);

    Map<String,String> map2 = new HashMap<String,String>();
    map2.put("key4", "value4");
    map2.put("key5", "value5");
    map2.put("key6", "value6");
    map.putAll(map2);

    System.out.println(map);
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Map.Entry in a Map
  2. How to get key and value from the Map.Entry
Home » Java Tutorial » Map
Map interface
Map element adding
Map.Entry class
Map key
Map value
Map key/value search
Map delete/remove
Map comparison
HashMap Class
HashMap search
HashMap clone
TreeMap
TreeMap key
TreeMap head sub map
TreeMap tail sub map
TreeMap sub map
NavigableMap
NavigableMap key
NavigableMap key-value pair
LinkedHashMap Class
IdentityHashMap
SortedMap