Map interface
In this chapter you will learn:
What is Map interface
A map is a group of key/value pairs. A map cannot contain duplicate keys. Each key can map to at most one value.
Maps are described by the Map
interface.
Map
interface has no parent interface and is declared as
Map<K,V>
- K is the key's type
- V is the value's type
Unlike List
, Set
, and
Queue
, Map
does not extend Collection.
It is possible to get a Collection
instance
by calling Map
's keySet()
, values()
,
and entrySet()
methods,
which respectively return a Set
of keys,
a Collection of values, and a Set of key/value pair entries.
The following code creates a Map
from HashMap
. We will talk about
HashMap
later. HashMap
is one of the implementation Java platform
provided.
Also the Map
is defined in a generic way that it only accepts string pair.
import java.util.HashMap;
import java.util.Map;
//from j av a 2s .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);
}
}
The code above generates the following result.
The toString
implementation from HashMap
is very readable and good for
debug.
Get the size of a Map
The size of a map is the count of key-value pairs.
import java.util.HashMap;
import java.util.Map;
//from j a v a 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");
System.out.println(map.size());
}
}
The code above generates the following result.
Next chapter...
What you will learn in the next chapter: