What are the various methods for iterating over a map in Java?

In JavaScript, there are several methods to iterate over a map object.

  1. Looping through with the for…of statement:
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of myMap) {
  console.log(`${key} = ${value}`);
}
  1. Utilizing the forEach method:
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
myMap.forEach((value, key) => {
  console.log(`${key} = ${value}`);
});
  1. Combine the entries() method with the for…of loop.
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let [key, value] of myMap.entries()) {
  console.log(`${key} = ${value}`);
}
  1. Combine the for…of loop with the keys() method and the values() method:
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
for (let key of myMap.keys()) {
  console.log(key);
}
for (let value of myMap.values()) {
  console.log(value);
}

These methods can be chosen according to specific needs, making it easy to traverse keys, values, or key-value pairs of a map object.

Leave a Reply 0

Your email address will not be published. Required fields are marked *