如何优雅地交换 Map 中的键和值

How to swap keys and values in a Map elegantly(如何优雅地交换 Map 中的键和值)
本文介绍了如何优雅地交换 Map 中的键和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道如何以艰难的方式完成它并让它工作 - 迭代条目并手动"交换.但我想知道是否可以像许多任务一样以更优雅的方式解决这个问题.

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 中的键和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How can create a producer using Spring Cloud Kafka Stream 3.1(如何使用Spring Cloud Kafka Stream 3.1创建制片人)
Insert a position in a linked list Java(在链接列表中插入位置Java)
Did I write this constructor properly?(我是否正确地编写了这个构造函数?)
Head value set to null but tail value still gets displayed(Head值设置为空,但仍显示Tail值)
printing nodes from a singly-linked list(打印单链接列表中的节点)
Control namespace prefixes in web services?(控制Web服务中的命名空间前缀?)