Explain Codes LogoExplain Codes Logo

Printing HashMap In Java

java
hashmap
iterative
performance
Anton ShumikhinbyAnton Shumikhin·Aug 9, 2024
TLDR

Succinctly print a HashMap like this:

hashMap.forEach((k, v) -> System.out.println(k + "=" + v));

A lambda expression leverages the forEach() method for efficient iteration and printing of key-value pairs.

In a situation where only certain values are needed:

for (String key : hashMap.keySet()) { System.out.println(key + "=" + hashMap.get(key)); }

This targets specific keys in your iterative loop to return their corresponding values. // Code says: "Key, your secret Value. Please, reveal yourself!"

Display HashMap entries

Representing a HashMap visually:

Key: | Value: ---------|--------- Color | Blue Size | Medium Material | Cotton

Highlighting its contents using different iterative approaches:

entrySet() magic

for (Map.Entry<String, String> entry : hashMap.entrySet()) { System.out.println(entry.getKey() + " - " + entry.getValue()); }

Iterates over entries rather than keys, saving us from calling get() over and over. // No need to badger each key with get() calls!

Key spree

for (String key : hashMap.keySet()) { System.out.println("Key: " + key + " Value: " + hashMap.get(key));// Key : "Sure, Value is ...." }

Direct emphasis on keys, allowing us to fetch each key's value. //Code whispers: "Dear Key, tell me your secret Value!"

Values galore

for (String value : hashMap.values()) { System.out.println("Value: " + value); }

This one's for the times you're interested in values only and couldn't care less about their keys. // Code: "Value, is that you? I've been expecting you!"

Decoding HashMap capacities

Revisiting the size and capacity of a HashMap:

  • The size() method counts key-value pairs (entries), returning a positive integer, not zero or negative.
  • Initial capacity and load factor walk hand in hand, silently determining HashMap performance.

Note, zero-based numbering refers to lists and arrays; not applicable to HashMap size.