Creating ordered maps

Maps have a sort() method, just like lists. They even use the same default comparator function. To preserve the order of the map after sort() has been called, you can use toOrderedMap() to convert it, as follows:

const myMap = Map.of(
'three', 3,
'one', 1,
'four', 4,
'two', 2
);
const mySortedMap = myMap
.toOrderedMap()
.sort();

myMap.forEach(
(v, k) => console.log('myMap', `${k} => ${v}`)
);
// -> myMap three => 3
// -> myMap one => 1
// -> myMap four => 4
// -> myMap two => 2

mySortedMap.forEach(
(v, k) => console.log('mySortedMap', `${k} => ${v}`)
);
// -> mySortedMap one => 1
// -> mySortedMap two => 2
// -> mySortedMap three => 3
// -> mySortedMap four => 4

The semantics of sort() are the same for lists and maps, as you can see by the sorted output. The iteration order of mySortedMap will always be the same, because it's an OrderedMap. When the sort happens, a new ordered map is created with the values in the expected order and an internal index to guarantee iteration order.

If you're calling sort() on a Map, the toOrderedMap() call isn't needed because an OrderedMap instance is returned. On the other hand, there's no real downside to including the call, and it serves to communicate intent.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.227.190.93