How to Efficiently Iterate Over Each Entry in a Java Map

How do I efficiently iterate over each entry in a Java Map?

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

On Java 10+:

for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}

How do I efficiently iterate over each entry in a Java Map?

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

On Java 10+:

for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}

Java : Iteration through a HashMap, which is more efficient?

Your second option is definitely more efficient since you are doing a lookup only once compared to n number of times in the first option.

But, nothing sticks better than trying it out when you can. So here goes -

(Not perfect but good enough to verify assumptions and on my machine anyway)

public static void main(String args[]) {

Map<String, Integer> map = new HashMap<String, Integer>();
// populate map

int mapSize = 500000;
int strLength = 5;
for(int i=0;i<mapSize;i++)
map.put(RandomStringUtils.random(strLength), RandomUtils.nextInt());

long start = System.currentTimeMillis();
// alt. #1
for (String key : map.keySet()) {
Integer value = map.get(key);
// use key and value
}
System.out.println("Alt #1 took "+(System.currentTimeMillis()-start)+" ms");

start = System.currentTimeMillis();
// alt. #2
for (Map.Entry<String, Integer> entry : map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
// use key and value
}
System.out.println("Alt #2 took "+(System.currentTimeMillis()-start)+" ms");
}

RESULTS (Some interesting ones)

With int mapSize = 5000; int strLength = 5;

Alt #1 took 26 ms

Alt #2 took 20 ms

With int mapSize = 50000; int strLength = 5;

Alt #1 took 32 ms

Alt #2 took 20 ms

With int mapSize = 50000; int strLength = 50;

Alt #1 took 22 ms

Alt #2 took 21 ms

With int mapSize = 50000; int strLength = 500;

Alt #1 took 28 ms

Alt #2 took 23 ms

With int mapSize = 500000; int strLength = 5;

Alt #1 took 92 ms

Alt #2 took 57 ms

...and so on

How do I efficiently iterate over each entry in a Java Map?

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

On Java 10+:

for (var entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}

Iterating through a map many times efficiently

Instead of maintaining a Map and a List, you could use Map.keySet to get the domains.

for (String domain : cookieMap.keySet()) {
if (host.contains(domain)) {
CookieList list = cookieMap.get(domain);
}
}

There is nothing inefficient about this, since the for loop is O(n), and the call to cookieMap is O(1).

Iterate through a HashMap

Iterate through the entrySet() like so:

public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove(); // avoids a ConcurrentModificationException
}
}

Read more about Map.

How to iterate through a Map in java?

For basic utilisation, the HashMap is the best, I've put how to iterate over it, easier than using an iterator :

public static void main (String[] args) {
//a map with key type : String, value type : String
Map<String,String> mp = new HashMap<String,String>();
mp.put("John","Math"); mp.put("Jack","Math"); map.put("Jeff","History");

//3 differents ways to iterate over the map
for (String key : mp.keySet()){
//iterate over keys
System.out.println(key+" "+mp.get(key));
}

for (String value : mp.values()){
//iterate over values
System.out.println(value);
}

for (Entry<String,String> pair : mp.entrySet()){
//iterate over the pairs
System.out.println(pair.getKey()+" "+pair.getValue());
}
}

A quick explanation :

for (String name : mp.keySet()){
//Do Something
}

means : "For all string from the keys of the map, we'll do something, and at each iteration we will call the key 'name' (it can be whatever you want, it's a variable)


Here we go :

public String[] getAllKeys(){ 
int i = 0;
String allkeys[] = new String[buckets.length];
KeyValue val = buckets[i];

//Look at the first one
if(val != null) {
allkeys[i] = val.key;
i++;
}

//Iterate until there is no next
while(val.next != null){
allkeys[i] = val.next.key;
val = val.next;
i++;
}

return allkeys;
}

How/Can I write a for each loop with a Hashmap in java?

You can iterate over the set of entries:

for (Entry<String, Boolean> book : library.entrySet()) {
if (book.getValue()) {
System.out.println(book.getKey());
}
}

Map.entrySet() returns a Set of entries (java.util.Map.Entry). Each entry contains a pair with a key and its value.

Java: can't use Map.Entry to iterate over a Map?

This is happening because you are using raw types: a List<LinkedHashMap> instead of a List<LinkedHashMap<Something, SomethingElse>>. As a result, the entrySet is just a Set instead of a Set<Map.Entry<Something, SomethingElse>>. Don't do that.



Related Topics



Leave a reply



Submit