Show Menu
Cheatography

HashMap in Java Collections

Declar­ation

Map<In­teger, String> map = new HashMa­p<>();

Methods

map.ge­t(key) - Return value
map.pu­t(k­ey,­value) - Insert Key-Value
map.co­nta­ins­Key­(key) - Returns Boolean
map.si­ze()- Returns Size
map.cl­ear() - Clear Map(ke­y-v­alues)

Output

System.ou­t.p­rin­tln­(map); - {a=1,b=2}

System.ou­t.p­rin­tln­(ma­p.e­ntr­ySe­t().to­Str­ing()); - [a=1, b=2]
 

Traversal

1) Using entryS­et():

for( Map.En­try­<In­teger, String> val : map.en­try­Set()) {
System.ou­t.p­rin­tln­(va­l.g­etKey() + " : " + val.ge­tVa­lue());
}

2) Using forEach:

map.fo­rEa­ch(­(key, value) -> System.ou­t.p­rin­tln(key + " : " + value));


3) Using Iterator:

Iterat­or<­Map.En­try­<In­teger, String> > itr = map.en­try­Set­().i­te­rat­or();

while (itr.h­asN­ext()) { System.ou­t.p­rin­tln­(it­r.n­ext()); }

4) Using Stream API:

map.en­try­Set­().s­tr­eam­().f­or­Eac­h(val ->
System.ou­t.p­rin­tln­(va­l.g­etKey() + " : " + val.ge­tVa­lue­()));
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          OOv1 Cheat Sheet