如何优雅地交换地图中的键和值 [英] How to swap keys and values in a Map elegantly

查看:141
本文介绍了如何优雅地交换地图中的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道如何做到这一点,让它工作 - 迭代的条目和交换手动。但我想知道,像这么多的任务,这一个可以解决在一个更优雅的方式。

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).

我可以假设我的地图是双射的,btw: )

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.

你可以做的是创建一个包含两个映射的包装类,并且执行一个双重 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.

这篇关于如何优雅地交换地图中的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆