What are the various methods for iterating over a map in Java?
In JavaScript, there are several methods to iterate over a map object.
- 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}`);
}
- Utilizing the forEach method:
const myMap = new Map([['a', 1], ['b', 2], ['c', 3]]);
myMap.forEach((value, key) => {
console.log(`${key} = ${value}`);
});
- 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}`);
}
- 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.