Advertisement
HashMap() |
---|
This constructor creates an empty HashMap to hold a particular type of key-value pair objects. Example - |
HashMap <String,Integer> hm = new HashMap <String,Integer>();
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. |
import java.util.*;
class HashMapDemo
{
public static void main(String... ar)
{
HashMap <String,Integer> hm = new HashMap <String,Integer>();
hm.put("Max", 1000);
hm.put("John", 4000);
hm.put("Tom", 2000);
hm.put("Ana", 6000);
hm.put("Rick", 5000);
System.out.println(hm);
System.out.println("Value at the key, Tom is "+ hm.get("Tom"));
System.out.println("Value at the key, Ana is "+ hm.get("Ana"));
}
}
{Max=1000, Tom=2000, John=4000, Rick=5000, Ana=6000}
Value at the key Tom is 2000
Value at the key Ana is 6000
Advertisement
import java.util.*;
class HashMapDemo
{
public static void main(String... ar)
{
HashMap <String,Integer> hm = new HashMap <String,Integer>();
hm.put("Max", 1000);
hm.put("John", 4000);
hm.put("Tom", 2000);
hm.put("Ana", 6000);
hm.put("Rick", 5000);
System.out.println("Iterating HashMap using Map.Entry in a for-each loop");
Set<Map.Entry<String,Integer>> set = hm.entrySet();
for(Map.Entry<String,Integer> mapE : set)
{
System.out.print(mapE.getKey() + " : ");
System.out.println(mapE.getValue());
}
}
}
Iterating HashMap using Map.Entry in a for-each loop
Max : 1000
Tom : 2000
John : 4000
Rick : 5000
Ana : 6000
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement