How to swap keys and values in a Map elegantly

前端 未结 8 1869
滥情空心
滥情空心 2020-12-25 14:49

I already know how to do it the hard way and got it working - iterating over entries and swapping \"manually\". But i wonder if, like so many tasks, this one can be solved

8条回答
  •  轮回少年
    2020-12-25 15:07

    Maps are not like lists, which can be reversed by swapping head with tail.

    Objects in maps have a computed position, and using the value as key and the key as value would requiere to re-compute the storage place, essentialy building another map. There is no elegant way.

    There are, however, bidirectional maps. Those may suit your needs. I'd reconsider using third-party libraries.

提交回复
热议问题