You are on page 1of 6

Java

HashMap/Hashtable,
LinkedHashMap and
TreeMap
Average rating 6 out of 10. Total 11
users rated.
<<Previous Next>>
Introduction
The basic idea of a map is that it maintains key-value associations
(pairs) so you can look up a value using a key. In this tutortial we
will discuss Java HashMap/Hashtable, LinkedHashMap and
TreeMap.
HashMap/Hashtable
HashMap has implementation based on a hash table. (Use this
class instead of Hashtable which is legacy class) .The HashMap
gives you an unsorted, unordered Map. When you need a Map
and you don't care about the order (when you iterate through it),
then HashMap is right choice. Keys of HashMap is like Set means
no duplicates allowed and unordered while values can be any
object even null or duplicate is also allowed. HashMap is very
much similar to Hashtable only difference is Hashtable has all
method synchronized for thread safety while HashMap has
non-synchronized methods for better performance.
We can visualize HashMap as below diagram where we have
keys as per hash-code and corresponding values.
HashMap provides constant-time performance for inserting and
locating pairs. Performance can be adjusted via constructors that
allow you to set the capacity and load factor of the hash table.
HashMap Constructors
Default HashMap Constructor (with default capacity of 16 and load
factor 0.75)
This is used to create HashMap based on existing map
Java HashMap, LinkedHashMap and TreeMap - w3resource http://www.w3resource.com/java-tutorial/java-maps.php
1 of 6 8/25/2014 12:59 PM
This is used to create HashMap based on existing map
implementation m.
This is used to initialize HashMap with capacity and default load
factor.
This is used to initialize HashMap with capacity and custom load
factor.
The basic operations of HashMap (put, get, containsKey,
containsValue, size, and is Empty) behave exactly like their
counterparts in Hashtable. HashMap has toString( ) method
overridden to print the key-value pairs easily. The following
program illustrates HashMap. It maps names to salary. Notice how
a set-view is obtained and used.
Java Code
view plain print ?
package hashmap; 01.
02.
import java.util.*; 03.
04.
public class EmployeeSalaryStoring { 05.
06.
public static void mainString!" args# { 0$.
%%&elo' (ine 'ill )reate *ash+ap 'ith initial si,e 10 an- 0.5 loa 0..
+ap/String0 1nteger2empSal 3 new *ash+ap/String0 1nteger2 04.
%%5--ing employee name an- salary to map 10.
empSal.put67amesh60 10000#; 11.
empSal.put6Suresh60 20000#; 12.
empSal.put6+ahesh60 30000#; 13.
empSal.put68aresh60 1000#; 14.
empSal.put68ainesh60 15000#; 15.
empSal.put67a9esh60 10000#; %% :upli)ate ;alue also allo'e- <ut 16.
empSal.put68ilesh60 null#; %%;alue )an <e null as 'ell 1$.
1..
System.out.println6=riginal +ap> 6? empSal#;%% @rinting Aull +ap 14.
20.
%%5--ing ne' employee the +ap to see or-ering oA o<je)t )hanges 21.
empSal.put67ohit60 23000#; 22.
%%7emoving one 9eyBvalue pair 23.
empSal.remove68ilesh6#; 24.
System.out.println6Cp-ate- +ap> 6?empSal#;%% @rinting Aull +ap 25.
%%@rinting all Deys 26.
System.out.printlnempSal.9eySet##; 2$.
%%@rinting all ;alues 2..
System.out.printlnempSal.values##; 24.
E 30.
E 31.
Output
Java LinkedHashMap
Java HashMap, LinkedHashMap and TreeMap - w3resource http://www.w3resource.com/java-tutorial/java-maps.php
2 of 6 8/25/2014 12:59 PM
Java LinkedHashMap
LinkedHashMap extends HashMap. It maintains a linked list of the
entries in the map, in the order in which they were inserted. This
allows insertion-order iteration over the map. That is,when
iterating through a collection-view of a LinkedHashMap, the
elements will be returned in the order in which they were inserted.
Also if one inserts the key again into the LinkedHashMap the
original orders is retained. This allows insertion-order iteration
over the map. That is, when iterating a LinkedHashMap, the
elements will be returned in the order in which they were inserted.
You can also create a LinkedHashMap that returns its elements in
the order in which they were last accessed.
Constructors
This constructor constructs an empty insertion-ordered
LinkedHashMap instance with the default initial capacity (16) and
load factor (0.75).
This constructor constructs an empty LinkedHashMap with the
specified initial capacity.
This constructor constructs an empty LinkedHashMapwith the
specified initial capacity and load factor.
This constructor constructs a insertion-ordered Linked HashMap
with the same mappings as the specified Map.
This constructor construct an empty LinkedHashMap instance with
the specified initial capacity, load factor and ordering mode.
Important methods supported by LinkedHashMap
Removes all mappings from the map.
Returns true if this map maps one or more keys to the specified
value.
Java HashMap, LinkedHashMap and TreeMap - w3resource http://www.w3resource.com/java-tutorial/java-maps.php
3 of 6 8/25/2014 12:59 PM
Returns true if this map maps one or more keys to the specified
value.
Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
Returns true if this map should remove its eldest entry.
Java Program demonstrate use of LinkedHashMap:
Java Code
view plain print ?
package lin9e-hashmap; 01.
02.
import java.util.(in9e-*ash+ap; 03.
import java.util.+ap; 04.
05.
public class (in9e-*ash+ap:emo { 06.
public static void main String args!"#{ 0$.
%%*ere 1nsertion or-er maintains 0..
+ap/1nteger0 String2lmap 3 new (in9e-*ash+ap/1nteger0 String2#; 04.
10.
lmap.put120 6+ahesh6#; 11.
lmap.put50 68aresh6#; 12.
lmap.put230 6Suresh6#; 13.
lmap.put40 6Sa)hin6#; 14.
System.out.println6(in9e-*ash+ap <eAore mo-iAi)ation6 15.
System.out.println61s Employee 1: 12 eFists> 6 ?lmap.)ontainsDey 16.
System.out.println61s Employee name 5mit EFists> 6 1$.
System.out.println6Gotal num<er oA employees> 6 1..
System.out.println67emoving Employee 'ith 1: 5> 6 14.
System.out.println67emoving Employee 'ith 1: 3 'hi)h -oes not e 20.
System.out.println6(in9e-*ash+ap 5Ater mo-iAi)ation6 21.
E 22.
E 23.
Output
Java TreeMap
A TreeMap is a Map that maintains its entries in ascending order,
sorted according to the keys' natural ordering, or according to a
Comparator provided at the time of the TreeMap constructor
argument.The TreeMap class is efficient for traversing the keys in
a sorted order. The keys can be sorted using the Comparable
interface or the Comparator interface. SortedMap is a subinterface
of Map, which guarantees that the entries in the map are sorted.
Additionally, it provides the methods firstKey() and lastKey() for
returning the first and last keys in the map, and headMap(toKey)
and tailMap(fromKey) for returning a portion of the map whose
Java HashMap, LinkedHashMap and TreeMap - w3resource http://www.w3resource.com/java-tutorial/java-maps.php
4 of 6 8/25/2014 12:59 PM
Additionally, it provides the methods firstKey() and lastKey() for
returning the first and last keys in the map, and headMap(toKey)
and tailMap(fromKey) for returning a portion of the map whose
keys are less than toKey and greater than or equal to fromKey.
TreeMap Constructors
Default TreeMap Constructor
This is used to create TreeMap based on existing map
implementation m.
This is used to create TreeMap based on existing map
implementation m.
This is used to create TreeMap with ordering based on
comparator output.
Java Program which explain some important methods of tree map.
Java Code
view plain print ?
package treemap; 01.
02.
import java.util.+ap; 03.
import java.util.Gree+ap; 04.
05.
public class Gree+ap:emo { 06.
0$.
public static void mainString!" args# { 0..
%%Hreating +ap oA Iruit an- pri)e oA it 04.
+ap/String0 1nteger2 t+ap 3 new Gree+ap/String0 1nteger2#; 10.
t+ap.put6=range60 12#; 11.
t+ap.put65pple60 25#; 12.
t+ap.put6+ango60 45#; 13.
t+ap.put6Hhi)9u60 10#; 14.
t+ap.put6&anana60 4#; 15.
t+ap.put6Stra'<erry60 40#; 16.
1$.
System.out.println6Sorte- Iruit <y 8ame> 6?t+ap#; 1..
t+ap.put6@inapple60 .$#; 14.
t+ap.remove6Hhi)9u6#; 20.
System.out.println6Cp-ate- Sorte- Iruit <y 8ame> 6 21.
22.
E 23.
E 24.
Output
Java Code
Java HashMap, LinkedHashMap and TreeMap - w3resource http://www.w3resource.com/java-tutorial/java-maps.php
5 of 6 8/25/2014 12:59 PM
Java Code
view plain print ?
package treemap; 01.
02.
import java.util.*; 03.
04.
public class Hount=))urren)e=AJor-s { 05.
public static void mainString!" args# { 06.
%% Set teFt in a string 0$.
String teFt 3 6Koo- morning )lass. *ave a goo- learning )lass. En 0..
04.
%% Hreate a Gree+ap to hol- 'or-s as 9ey an- )ount as value 10.
Gree+ap/String0 1nteger2 map 3 new Gree+ap/String0 1nteger2#; 11.
12.
String!" 'or-s 3 teFt.split6 6#; %%Splitting sentan)e <ase- on S 13.
for int i 3 0; i / 'or-s.length; i??# { 14.
String 9ey 3 'or-s!i".to(o'erHase#; 15.
16.
if 9ey.length# 2 0# { 1$.
if map.get9ey# 33 null# { 1..
map.put9ey0 1#; 14.
E else { 20.
int value 3 map.get9ey#.int;alue#; 21.
value??; 22.
map.put9ey0 value#; 23.
E 24.
E 25.
E 26.
System.out.printlnmap#; 2$.
E 2..
E 24.
Output
Summary
Map is collection of key-value pair (associate) objects collection
HashMap allows one null key but Hashtable does not allow any null keys.
Values in HashMap can be null or duplicate but keys have to be unique.
Iteration order is not constant in case of HashMap.
When we need to maintain insertion order while iterating we should use
LinkedHashMap.
LinkedHashMap provides all the methods same as HashMap.
LinkedHashMap is not thread safe.
TreeMap has faster iteration speed compare to other map implementation.
TreeMap is sorted order collection either natural ordering or custom ordering as
per comparator.
Author : Amit Himani
Java HashMap, LinkedHashMap and TreeMap - w3resource http://www.w3resource.com/java-tutorial/java-maps.php
6 of 6 8/25/2014 12:59 PM

You might also like