0% found this document useful (0 votes)
30 views6 pages

10 Java HashMap Examples Explained

This document provides 10 examples of using a HashMap in Java. It begins with basic examples like creating a HashMap, adding key-value pairs, retrieving values, and iterating over the HashMap. It also covers more advanced examples like checking the size of the HashMap, clearing it, checking if a key or value exists, checking if the HashMap is empty, removing objects, and sorting the HashMap. The examples demonstrate common use cases for HashMaps in Java programs.

Uploaded by

Bellum Letale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views6 pages

10 Java HashMap Examples Explained

This document provides 10 examples of using a HashMap in Java. It begins with basic examples like creating a HashMap, adding key-value pairs, retrieving values, and iterating over the HashMap. It also covers more advanced examples like checking the size of the HashMap, clearing it, checking if a key or value exists, checking if the HashMap is empty, removing objects, and sorting the HashMap. The examples demonstrate common use cases for HashMaps in Java programs.

Uploaded by

Bellum Letale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

7/1/2015

10ExamplesofHashMapinJavaProgrammingTutorial|Java67

Java67
JavaProgrammingtutorialsandInterviewQuestions
Monday,February25,2013

10ExamplesofHashMapinJavaProgrammingTutorial
[Link]
HashMapworksinJava,whichdescribestheorypartofJavaHashMap,Ithoughttoshare,Howtouse
HashMapinJavawithfundamentalHashMapexamples,butcouldn'[Link]
isaadatastructure,basedonhashing,whichallowsyoutostoreobjectaskeyvaluepair,advantageof
usingHashMapisthat,youcanretrieveobjectonconstanttimei.e.O(1),[Link]
implementsMapinterfaceandsupportsGenericsfromJava1.5release,[Link]
arecoupleofmoreCollections,whichprovidessimilarfunctionalitieslikeHashMap,whichcanalsobeused
[Link],butHashtableissynchronizedandperformspoorinsingle
[Link],
relativelynewisConcurrentHashMap,whichprovidesbetterperformancethanHashtableinconcurrent
[Link]
[Link],wewillseedifferentexamplesofHashMap,likeaddingand
removingentries,iteratingoverJavaHashMap,checkingsizemap,findingifakeyorvalueexistsonMap
andvariousotherexamples,whichweusedfrequently.

JavaHashMapExample

Beforegoingtoseetheseexamples,[Link]
synchronized,sodon'[Link]
oferrorisclearingMapandreusingit,whichisperfectlyvalidinsinglethreadedenvironment
butifdoneinmultithreadedenvironmentcancreatesubtlebugs.

Laro
Libreng
Online
Games
Maglaro
Onlinesa
Facebook
Kasama1
Bilyon
User.
Libreng
Sumali!

JavaHashMapExample1:CreateandaddobjectsinHashMap
InfirstexampleofHashMap,[Link],ifyouare
[Link]
Integerwithdefaultsizeandloadfactor.

HashMap<String,Integer>cache=newHashMap<String,Integer>();

alternativelyyoucancreateHashMapfromcopyingdatafromanotherMaporHashtableasshownin
belowexample:

Hashtable<Integer,String>source=newHashtable<Integer,String>();
HashMap<Integer,String>map=newHashMap(source);

Youcanalsosupplyloadfactor(percentageofsize,whichiffulledtriggerresizeofHashMap)and
[Link],
alsocalledputoperation,[Link]
HashMap:

Followers

Jointhissite
withGoogleFriendConnect

BlogArchive

2015(40)

[Link](21,"TwentyOne");
[Link](21.0,"TwentyOne");//thiswillthrowcompilererrorbecause21.0isn
otinteger

Members(722

2014(68)
2013(49)
December(1)

JavaHashMapExample2:RetrievingvaluefromHashMap

November(3)

[Link],weneedtoknowkey

[Link]

Alreadyamember?

1/6

7/1/2015

10ExamplesofHashMapinJavaProgrammingTutorial|Java67

August(8)

[Link]'susethekeyinsertedinlastexample,[Link](key)methodisused

July(6)

togetvalueformHashMap:

June(2)
May(3)
April(2)

Integerkey=21;
Stringvalue=[Link](key);
[Link]("Key:"+key+"value:"+value);

March(7)
February(7)

Output:Key:21value:TwentyOne

JavaIterator
Example
10Examplesof
HashMapin
Java
Programmin
gTutor...
Difference
betweenJDK
andJREin
Java
Platform
Difference
betweenJIT
andJVMin
Java
Interview...
Canabstract
classhave
Constructor
inJava
Inte...
ClassinJava
andObject
oriented
programmin
glang...
Howto
connect
MySQL
database
fromJava
program
wi...
January(10)

87%

87%

87%

87%

44%

87%

87%

87%

33%

30%

JavaHashMapExample3:IteratingoverHashMap
[Link]
throughwholemapandperformoperationsoneachkeyvaluepair,[Link]
ordertouseIterator,wefirstneedSetofkeys,[Link]()[Link]
waytherearemultiplewaystoloopthroughMapinJava,seeherefor4waystoloopHashMapinJava.
[Link]:

[Link](21,"TwentyOne");
[Link](31,"ThirtyOne");
Iterator<Integer>keySetIterator=[Link]().iterator();
while([Link]()){
Integerkey=[Link]();
[Link]("key:"+key+"value:"+[Link](key));

87%

}
Output:

40%

80%

key:21value:TwentyOne
key:31value:ThirtyOne

RecommendedBooksandI

JavaHashMapExample4:SizeandClearinHashMap
TwofundamentalexampleofHashMap,isfindingouthowmanyelementsarestoredinMap,knownas
[Link]
size()andclear()[Link],hereiscodeexample.

2012(137)
[Link]("SizeofMap:"+[Link]());
[Link]();//clearshashmap,removesallelement
[Link]("SizeofMap:"+[Link]());
Output:
SizeofMap:2
SizeofMap:0

Top10CodingQues
ProgrammingJobIn

GoodJavaInterview
2to3yearsExperie
Programmers

21Frequentlyasked
Questions

20SQLQueryInterv
forJavaDevelopers

18GreatDesignPat
forJavaProgarmers

15JavaEnumbased
Questions
87%

YoucanreuseMapbyclearingit,butbecarefulifitsbeensharedbetweenmultiplethreadswithoutproper
[Link].I
suggestnottodo,untilyouhaveverygoodreasonofdoingit.

87%

40%
1,599

199
87%

57%

JavaHashMapExample5and6:ContainsKeyandContainsValueExample
InthisexampleofJavaHashMap,wewilllearnhowtocheckifMapcontainsaparticularobjectaskeyor
[Link](Objectkey)and
[Link]

2/6

7/1/2015

10ExamplesofHashMapinJavaProgrammingTutorial|Java67

containsValue(Objectvalue)[Link]

87%

87%

87%

44%

87%

87%

87%

87%

87%

87%

iscodeexample:

[Link]("DoesHashMapcontains21askey:"+[Link](21));
[Link]("DoesHashMapcontains21asvalue:"+[Link](21
));
[Link]("DoesHashMapcontainsTwentyOneasvalue:"+[Link]
Value("TwentyOne"));
Output:
DoesHashMapcontains21askey:true
DoesHashMapcontains21asvalue:false
DoesHashMapcontainsTwentyOneasvalue:true

69%

1,400

599

JavaHashMapExample7:CheckingifHashMapisempty
InthisMapexample,[Link]

87%

87%

outifMapisempty,oneisusingsize()method,[Link]
HashMapisemptyisusingmorereadableisEmpty()[Link]
codeexample:

booleanisEmpty=[Link]();

AdsbyGoogle

[Link]("IsHashMapisempty:"+isEmpty);

CoreJava
JavaHashmapEx

Output:

JavaProgrammin

IsHashMapisempty:false

JavaHashMapExample8:RemovingObjectsfromHashMap
[Link]
providesremove(Objectkey)method,[Link],
returnsnullorthevalueofentry,[Link]
HashMap:

Integerkey=21;
Objectvalue=[Link](key);
[Link]("FollowingvalueisremovedfromMap:"+value);
Output:
FollowingvalueisremovedfromMap:TwentyOne

JavaHashMapExample9:SortingHashMapinJava
HashMapisanunsortedMapinJava,[Link]
cansortitbaseduponkeyorvalue,seehowtosortHashMaponkeysandvaluesforfullcodeexample.
Alternatively,[Link]
andcancreateaMapsortedonnaturalorderofkeyoranycustomsortingorderdefinedbyComparator.
OnlythingiskeyshouldbenaturallycomparableandtherecompareTo()methodshouldn'tthrow
[Link]()methoddefinedforMapisonlyforListandits
[Link]
[Link]
naturalorderofkeys:
[Link]

3/6

7/1/2015

10ExamplesofHashMapinJavaProgrammingTutorial|Java67

[Link](21,"TwentyOne");
[Link](31,"ThirtyOne");
[Link](41,"ThirtyOne");
[Link]("UnsortedHashMap:"+map);
TreeMapsortedHashMap=newTreeMap(map);
[Link]("SortedHashMap:"+sortedHashMap);
Output:
UnsortedHashMap:{21=TwentyOne,41=ThirtyOne,31=ThirtyOne}
SortedHashMap:{21=TwentyOne,31=ThirtyOne,41=ThirtyOne}

JavaHashMapExample10:SynchronizedHashMapinJava
[Link]
onJava1.5andaboveconsiderusingConcurrentHashMapinplaceofsynchronizedHashMapbecauseit
providebetterconcurrency.IfyourprojectisstillonJDK1.4thanyougottouseeitherHashtableor
[Link](map)[Link]
[Link].

RelatedJavaProgrammingTutorialsfromJava67Blog
1. DifferencebetweenHashMapandArrayListinJava
2. HowtosortArrayListinascendingorderinJava
3. DifferencebetweenTreeMapandTreeSetinJava
4. WhentouseMap,ListandSetcollectioninJava
5. DifferencebetweenHashMapandHashSetinJava
6. DifferencebetweenIdentityHashMapandHashMapinJava
87%

87%

87%

40%

67%

88%

Youmightlike:

JavaCollection
interviewQuestions
Answers|Java
CollectionFAQ

HowtoRead,Write
XLSXFileinJava
ApachPOIExample

Differencebetween
Set,ListandMapin
JavaInterview
question

Differencebetween
Tree
MapandTree
SetinJava

Recommendedby

PostedbyJavinPaulat7:47AM

+13 Recommend this on Google

Labels:corejava,Javacollectiontutorial,JavaprogrammingTutorial

8comments:
May11,2013at12:23PM
Sofar,itisthebestintroarticleonHashMapsI'[Link]
HashMapusage.
Reply

[Link]

4/6

7/1/2015

10ExamplesofHashMapinJavaProgrammingTutorial|Java67

Zavier August18,2013at7:36PM
Do you know how to get all key value pair from HashMap using core Java library, without any
externallibrary?Ihavearequirement,whereIneedtoconvertallHashMapkeyvaluestoacolon
separated String e.g. key : value and send them to another system. I don't know how to convert
HashMap to String, as toString() format is not the one I wanted. I have an idea to write a static
method, which takes HashMap and returns a String with all key values pair separted by : and
individualentriessepratedbycomma(,)MyonlyproblemisIdon'tknowhowtogetallkeyvalues
fromMap?
Reply
Replies
Anonymous September3,2013at7:21AM
HiZavier,youcantrythis:
HashMapmap=newHashMap();//oryourhashmapalreadypopulated
for(Entryentry:[Link]()){
Stringkey=[Link]().toString();
Stringvalue=[Link]().toString();
//dowhatyouwantwiththesesstrings
}
Baptiste
Reply

Anonymous March19,2014at9:08AM
Veryniceexamples,thanks!
Justonequestion,ifwehavethepair(21,"TwentyOne")andwewanttochangeitto(21,"Twenty
Two")willthe
[Link](21,"TwentyTwo");commandwork?
Reply
Replies
Anonymous March26,2014at3:45AM
Ok,Ireadinjavadocs,itwill.
Reply

Anonymous July16,2014at1:35AM
[Link]
Reply

Anonymous September16,2014at12:08AM
goodtutorial
Reply

Anonymous June29,2015at1:59AM
[Link]
Reply

[Link]

5/6

7/1/2015

10ExamplesofHashMapinJavaProgrammingTutorial|Java67

Enteryourcomment...

Commentas:

Publish

GoogleAccount

Preview

NewerPost

Home

OlderPost

Subscribeto:PostComments(Atom)

PoweredbyBlogger.

[Link]

6/6

You might also like