问题描述
我已经知道如何以艰难的方式完成它并让它工作 - 迭代条目并手动"交换.但我想知道是否可以像许多任务一样以更优雅的方式解决这个问题.
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 in a more elegant way.
我已阅读这篇文章,很遗憾它确实阅读了没有优雅的解决方案.我也无法使用任何花哨的 Guava BiMaps 或 jdk 之外的任何东西(项目堆栈已经定义).
I have read this post, unfortunately it does not feature elegant solutions. I also have no possibility to use any fancy Guava BiMaps or anything outside the jdk (project stack is already defined).
我可以假设我的地图是双射的,顺便说一句:)
I can assume that my map is bijective, btw :)
推荐答案
标准的 API/Java 运行时不提供双向映射,因此唯一的解决方案是遍历所有条目并手动交换它们.
The standard API / Java runtime doesn't offer a bi-directional map, so the only solution is to iterate over all entries and swap them manually.
p>
您可以做的是创建一个包含两个映射并在内部执行双重 put()
的包装类,因此您可以快速查看数据的两个视图.
What you can do is create a wrapper class which contains two maps and which does a dual put()
internally so you have fast two views on the data.
另外,由于开源,您不必包含第三方库,您可以简单地将所需的类复制到您自己的项目中.
Also, thanks to open source, you don't have to include a third party library, you can simply copy the classes you need into your own project.
这篇关于如何优雅地交换 Map 中的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!