Friday, May 27, 2011

Map interface methods (java)

Here are some of the most useful Map methods. m is a Map, b is a boolean, i is an int, set is a Set, col is a Collection, key is an Object used as the key used to store a value, val is an Object stored as the value associated with the key.
ResultMethod Description
Adding key-value pairs to a map
obj = m.put(key, val) Creates mapping from key to val. It returns the previous value (or null) associated with the key.

m.putAll(map2) Adds all key-value entries from another map, map2.
Removing key-value pairs from a map

m.clear() Removes all elements from a Map
objm.remove(key) Deletes mapping from key to anything. Returns previous value (or null) associated with the key.
Retrieving information from the map
bm.containsKey(key) Returns true if m contains a key key
bm.containsValue(val) Returns true if m contains val as one of the values
objm.get(key) Returns value corresponding to key, or null if there is no mapping. If null has been stored as a value, use containsKey to see if there is a mapping.
bm.isEmpty() Returns true if m contains no mappings.
im.size() Returns number of mappings in m.
Retrieving all keys, values, or key-value pairs (necessary for iteration)
setm.entrySet() Returns set of Map.Entry values for all mappings.
setm.keySet() Returns Set of keys.
colm.values() Returns a Collection view of the values in m.

No comments:

Post a Comment