Here's a simple example to demonstrate Map
usage:
Map<String, String> map = new HashMap<String, String>();
map.put("Color1","Red");
map.put("Color2","Blue");
map.put("Color3","Green");
map.put("Color4","White");
System.out.println(map);
// {Color4=White, Color3=Green, Color1=Red, Color2=Blue}
System.out.println(map.get("Color2")); // Blue
System.out.println(map.keySet());
// [Color4, Color3, Color1, Color2]
for (Map.Entry<String,String> entry : map.entrySet()) {
System.out.printf("%s -> %s%n", entry.getKey(), entry.getValue());
}
// Color4 -> White
// Color3 -> Green
// Color1 -> Red
// Color2 -> Blue
Note that the entries are iterated in arbitrary order. If you need a specific order, then you may consider e.g. LinkedHashMap
See also
Related questions
On iterating over entries:
On different Map
characteristics:
On enum
You may want to consider using an enum
and EnumMap
instead of Map<String,String>
.
See also
Related questions
keySet()
, not just the descriptions. – Superhuman