Advertisement
Classes | Description |
---|---|
AbstractMap | An abstract class but still provides most of the implementation of Map interface, to minimize the effort required by other classes to implement it. |
HashMap | This class extends AbstractMap and uses Hash table to store the key-value pairs/map entries. Ordering of its elements may appear out-of-order. |
TreeMap | This class extends AbstractMap and it sorts its elements according to the natural ordering of its keys. |
LinkedHashMap | This class extends AbstractMap and it uses the insertion order of it's elements to provide a consistent ordering. |
interface Map<K,V>
Methods | Description |
---|---|
void clear() | Removes all the key/value pairs from the HashMap. |
int size() | Returns the total number of key-value pairs in a HashMap. |
boolean isEmpty() | Returns true if HashMap has no key-value pair in it. |
V get(Object key) | Returns the value associated with a specified key. |
put(K key, V value) | Puts the specified key and its associated value in the HashMap. |
boolean containsKey(Object key) | Returns true if HashMap contains a particular key, otherwise false. |
Set<Map.Entry<K,V>> entrySet() | Returns the Set containing Map.Entry objects. |
Advertisement
Methods | Description |
---|---|
K getKey() | This method returns the key of the current map entry or current key-value pair. |
V getValue() | This method returns the value of a current map entry or current key-value pair. |
int hashCode() | This method returns the hash code of current key-value pair. |
import java.util.*;
class HashMapDemo
{
public static void main(String... ar)
{
Map <String,Integer> hm = new HashMap <String,Integer>();
hm.put("Max", 1);
hm.put("John", 4);
hm.put("Tom", 2);
hm.put("Ana", 6);
hm.put("Rick", 5);
System.out.println("Iterating TreeMap using Map.Entry and for-each loop");
Set<Map.Entry<String,Integer>> set = tm.entrySet();
//for-each loop to iterate each element of Map, using Map.Entry objects and methods
for(Map.Entry <String,Integer> me : set)
System.out.print(getKey() +":");
System.out.println(getValue());
}
}
Iterating HashMap using Map.Entry in a for-each loop
Max:1
Tom:2
John:4
Ana:6
Rick:5
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement