Java - Swapping Values and Keys in one Map?

2019-08-04 18:07发布

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.

2条回答
三岁会撩人
2楼-- · 2019-08-04 18:54

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.

查看更多
男人必须洒脱
3楼-- · 2019-08-04 19:08

Sounds like you want a Bi-Directional Map, something like Guava BiMap

查看更多
登录 后发表回答