Cheatography
https://cheatography.com
HashMap in Java Collections
Declaration
Map<Integer, String> map = new HashMap<>(); |
Methods
map.get(key) - Return value
map.put(key,value) - Insert Key-Value
map.containsKey(key) - Returns Boolean
map.size()- Returns Size
map.clear() - Clear Map(key-values) |
Output
System.out.println(map); - {a=1,b=2}
System.out.println(map.entrySet().toString()); - [a=1, b=2] |
|
|
Traversal
1) Using entrySet():
for( Map.Entry<Integer, String> val : map.entrySet()) {
System.out.println(val.getKey() + " : " + val.getValue());
}
2) Using forEach:
map.forEach((key, value) -> System.out.println(key + " : " + value));
3) Using Iterator:
Iterator<Map.Entry<Integer, String> > itr = map.entrySet().iterator();
while (itr.hasNext()) { System.out.println(itr.next()); }
4) Using Stream API:
map.entrySet().stream().forEach(val ->
System.out.println(val.getKey() + " : " + val.getValue())); |
|
Created By
Metadata
Comments
No comments yet. Add yours below!
Add a Comment
Related Cheat Sheets