A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value. It models the mathematical function abstraction. The Map interface includes methods for basic operations (such as put, get, remove, containsKey, containsValue, size, and empty), bulk operations (such as putAll and clear), and collection views (such as keySet, entrySet, and values).
The most common Map implementations is HashMap.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package info.java.tips.map; import java.util.HashMap; import java.util.Map; public class MapDemo { public static void main(String[] args) { Map<String, String> map = new HashMap<String, String>(); map.put("1", "One"); map.put("2", "Two"); map.put("3", "Three"); for (Map.Entry<String, String> entry : map.entrySet()) { System.out.println(entry.getKey() + "->" + entry.getValue()); } } } |
Run The Application
Right click to the MapDemo class; select Run As -> Java Application.
Output
1 2 3 |
1->One 2->Two 3->Three |