Map value

In this chapter you will learn:

  1. How to get value set from a Map
  2. How to get a value from Map

Get value set from a Map

values() method from Map returns all values as a set.

import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
//j a  va 2  s.c  om
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");

    Collection set = map.values();
    Iterator iter = set.iterator();

    while (iter.hasNext()) {
      System.out.println(iter.next());
    }
  }
}

Get value by key

Once we know a key we can try to get its mapping value by calling get method.

import java.util.HashMap;
import java.util.Map;
/*j a v  a2s.com*/
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.get("key2"));
  }
}

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to check key existence in a Map
  2. How to check value existence in a Map
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