Map
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.
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, Color> colorMap = new HashMap<String, Color>();
colorMap.put("red", Color.RED);
colorMap.put("blue", Color.BLUE);
colorMap.put("green", Color.GREEN);
colorMap.put("RED", Color.RED);
for (String colorKey : colorMap.keySet()){
System.out.println(colorKey);
}
Collection<Color> colorValues = colorMap.values();
for (Iterator<Color> it = colorValues.iterator(); it.hasNext();){
System.out.println(it.next());
}
}
}
enum Color {
RED(255, 0, 0), GREEN(0, 255, 0), BLUE(0, 0, 255);
private int r, g, b;
private Color(int r, int g, int b) {
this.r = r;
this.g = g;
this.b = b;
}
@Override
public String toString() {
return "r = " + r + ", g = " + g + ", b = " + b;
}
}
red
blue
green
RED
r = 255, g = 0, b = 0
r = 0, g = 0, b = 255
r = 0, g = 255, b = 0
r = 255, g = 0, b = 0
The entrySet() method returns a Set of Map.Entry objects.