Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map() on an iterator

People also ask

Can iterator be used for map?

Remember that we cannot iterate over map directly using iterators, because Map interface is not the part of Collection. All maps in Java implements Map interface. There are following types of maps in Java: HashMap.

How do you traverse a map using iterator?

Iterating over Map. Map. entrySet() method returns a collection-view(Set<Map. Entry<K, V>>) of the mappings contained in this map. So we can iterate over key-value pair using getKey() and getValue() methods of Map.

Can you iterate through a map in JavaScript?

Iterate through a Map using JavaScript # Use the forEach() method to iterate over a Map object. The forEach method takes a function that gets invoked for each key/value pair in the Map , in insertion order. The function gets passed the value, key and the Map object on each iteration.

Can we use iterator in HashMap?

In Java HashMap, we can iterate through its keys, values, and key/value mappings.


The simplest and least performant way to do this is:

Array.from(m).map(([key,value]) => /* whatever */)

Better yet

Array.from(m, ([key, value]) => /* whatever */))

Array.from takes any iterable or array-like thing and converts it into an array! As Daniel points out in the comments, we can add a mapping function to the conversion to remove an iteration and subsequently an intermediate array.

Using Array.from will move your performance from O(1) to O(n) as @hraban points out in the comments. Since m is a Map, and they can't be infinite, we don't have to worry about an infinite sequence. For most instances, this will suffice.

There are a couple of other ways to loop through a map.

Using forEach

m.forEach((value,key) => /* stuff */ )

Using for..of

var myMap = new Map();
myMap.set(0, 'zero');
myMap.set(1, 'one');
for (var [key, value] of myMap) {
  console.log(key + ' = ' + value);
}
// 0 = zero
// 1 = one

You could define another iterator function to loop over this:

function* generator() {
    for (let i = 0; i < 10; i++) {
        console.log(i);
        yield i;
    }
}

function* mapIterator(iterator, mapping) {
    for (let i of iterator) {
        yield mapping(i);
    }
}

let values = generator();
let mapped = mapIterator(values, (i) => {
    let result = i*2;
    console.log(`x2 = ${result}`);
    return result;
});

console.log('The values will be generated right now.');
console.log(Array.from(mapped).join(','));

Now you might ask: why not just use Array.from instead? Because this will run through the entire iterator, save it to a (temporary) array, iterate it again and then do the mapping. If the list is huge (or even potentially infinite) this will lead to unnecessary memory usage.

Of course, if the list of items is fairly small, using Array.from should be more than sufficient.


This simplest and most performant way is to use the second argument to Array.from to achieve this:

const map = new Map()
map.set('a', 1)
map.set('b', 2)

Array.from(map, ([key, value]) => `${key}:${value}`)
// ['a:1', 'b:2']

This approach works for any non-infinite iterable. And it avoids having to use a separate call to Array.from(map).map(...) which would iterate through the iterable twice and be worse for performance.


Other answers here are... Weird. They seem to be re-implementing parts of the iteration protocol. You can just do this:

function* mapIter(iterable, callback) {
  for (let x of iterable) {
    yield callback(x);
  }
}

and if you want a concrete result just use the spread operator ....

[...iterMap([1, 2, 3], x => x**2)]