Java - 在一个Map中交换值和键? [英] Java - Swapping Values and Keys in one Map?

查看:121
本文介绍了Java - 在一个Map中交换值和键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的编程课程制作一个加密和解密程序,但是我比团队领先一年,所以我想我会用去年学到的东西来简化。我决定使用树形图。程序所做的是它接收一个文件,读取第一行,其中包含字母将如何编码的加密数据。它的格式如A-> B,B-> C,C-> A等,然后第2行和第3行的空行包含消息。我用了reg。表达式从文本文件中删除我不需要的字符,将键映射到第一个字母,然后将这些值设置为带箭头的字母。 (A是关键,B是值)所以如果消息说ABC,它将成为BCA。我想知道,至于解密,如果有一种方法可以轻松地将键和值翻转到输入的位置,A键= B val,它将交换为B key = A val。只是寻找比我目前使用集合和迭代器更简单的方法。

I am making an encrypt and decrypt program for my programming class, however I am a year ahead of the group so I thought I'd simplify things by using what I learned last year. I decided to use a Tree Map. What the program does is it takes in a file, reads the first line which contains the encrypt data of how the letters will be coded. It is in a format such as "A->B","B->C","C->A" etc. and then a blank line for line 2 and the third line contains the message. I used reg. expressions to remove the char's I do not need from the text file, mapped the Keys to the first letter and then set those values to the arrowed letter. (A is key, B is value) So if the message said ABC, it would become BCA. I am wondering, as for decrypting, if there was a way to easily flip the Keys and Values to where if input was, A key = B val, it would swap to B key = A val. Just looking for an easier method than what I am currently doing with collections and iterators.

推荐答案


寻找比我目前使用集合和迭代器更简单的方法。

Just looking for an easier method than what I am currently doing with collections and iterators.

这是你可能做到的唯一方法,原因是在一般地图中,可能有几个键映射到相同的值,在这种情况下,无法自动确定如何处理结果映射中的重复键。

This is the only way you could possibly do it, the reason being that in a general map, there could be several keys mapping to the same value, in which case there would be no way to automatically determine what to do with duplicate keys in the resulting map.

这篇关于Java - 在一个Map中交换值和键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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