MainMenu

Home Core Java Overview Maven Tutorials

Tuesday, 13 March 2018

What is Hashmap in Java? Hashmap vs HashTable


HashMap in java


Hi all, in this demo i will describe about HashMap in java.


Map Interface.
public interface Map
An object that maps key to values. A map cannot contain duplicate keys;each key can map to at most one value.
This interface takes the place of the Disctionary class, which was a totally Abstract Class rather than an interface.

HashMap is important for selenium as well as for interview also.
hashMap is a Map based collection class that is used for storing Key & Value(associated with keys).
1).It is donated as HashMap.
2).Hashmap contains only unique elements.
3).Hashmap may have only one null key and multiple null values
4). Hashmap maintains no order.

Here is the example of HashMap in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class hashmapdemo
{
public static void main(String args[])
{
hashmapdemo obj = new hashmapdemo();
obj.g();
}
public void g()
{
Map< String, Integer > record = new HashMap<>();
record.put("Anjana", 26);
record.put("Silpi", 27);
record.put("Heena", 28);
record.put("Adhiraj", 29);
System.out.println(record.get("Heena"));
Set<String> keys = record.keySet();
for(String i : keys)
{
System.out.println(i + ":" +record.get(i));
}
}
}

Output :

28
Adhiraj:29
Anjana:26
Silpi:27
Heena:28





TreeMap in Java

TreeMap is Red-Black tree based NavigableMap implementation. It is sorted according to the natural ordering of its keys.
TreeMap class implements Map interface similar to HashMap class.
The main difference between them is that HashMap is an unordered collection while TreeMap is sorted in the ascending order of its keys.
TreeMap is unsynchronized collection class which means it is not suitable for thread-safe operations until unless synchronized explicitly.

Here is the example of TreeMap in Java.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class hashmapdemo
{
public static void main(String args[])
{
hashmapdemo obj = new hashmapdemo();
obj.g();
}
public void g()
{
//Map<String, Integer> record = new HashMap<>();
TreeMap<Integer, String> record = new TreeMap<>();
record.put(26, "Anjana");
record.put(28, "Heena");
record.put( 29, "Adhiraj");
record.put(27, "Silpi");
System.out.println(record.get(28));
for(Integer i : record.keySet())
{
System.out.println(i + ":" +record.get(i));
}
}
}


Output :

Heena
26:Anjana
27:Silpi
28:Heena
29:Adhiraj



HashMap vs TreeMap

No comments:

Post a Comment