Вот фрагмент, демонстрирующий большинство функций Map
:
import java.util.*;
public class MapExample {
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("One", 1);
map.put("Two", 2);
map.put("Three", 3);
System.out.println(map.size()); // prints "3"
System.out.println(map);
// prints "{Three=3, One=1, Two=2}"
// HashMap allows null keys and values
// Map also allows several keys to map to the same values
map.put(null, 1);
map.put("?", null);
System.out.println(map.size()); // prints "5"
System.out.println(map);
// prints "{null=1, Three=3, ?=null, One=1, Two=2}"
// get values mapped by key
System.out.println(map.get("One")); // prints "1"
System.out.println(map.get("Two")); // prints "2"
System.out.println(map.get("Three")); // prints "3"
// get returns null if
// (i) there's no such key, or
// (ii) there's such key, and it's mapped to null
System.out.println(map.get("Four") == null); // prints "true"
System.out.println(map.get("?") == null); // prints "true"
// use containsKey to check if map contains key
System.out.println(map.containsKey("Four")); // prints "false"
System.out.println(map.containsKey("?")); // prints "true"
// use keySet() to get view of keys
Set<String> keys = map.keySet();
System.out.println(keys);
// prints "[null, Three, ?, One, Two]"
// the view supports removal
keys.remove("Three");
System.out.println(map);
// prints "{null=1, ?=null, One=1, Two=2}"
// use values() to get view of values
Collection<Integer> values = map.values();
System.out.println(values);
// prints "[1, null, 1, 2]"
// the view supports removal
values.remove(null);
System.out.println(map);
// prints "{null=1, One=1, Two=2}"
values.remove(1); // removes at most one mapping
System.out.println(map);
// prints "{One=1, Two=2}"
// iterating all entries using for-each
for (Map.Entry<String,Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "->" + entry.getValue());
}
// prints "One->1", "Two->2"
map.clear();
System.out.println(map.isEmpty()); // prints "true"
}
}