比较Java中的现有数据条目

时间:2021-03-25 22:52:47

I have a HashMap relating Keys to Strings, and I need to compare some of the Strings against each other. However, some of the Strings may or may not be in the HashMap.

我有一个HashMap将字符串与键相关联,我需要将一些字符串相互比较。但是,某些字符串可能在HashMap中,也可能不在HashMap中。

Example: Let's say I have 4 Strings that I plan to compare to each other if possible, but only 3 of them end up in the HashMap. How can I compare the Strings that are present without trying to compare them to the String that isn't, and without doing a bunch of nested ifs and elses?

示例:假设我有4个字符串,我打算在可能的情况下相互比较,但只有3个字符串最终出现在HashMap中。如何比较存在的字符串,而不是将它们与不匹配的字符串进行比较,而不进行一堆嵌套的ifs和elses?

edit: Alohci's solution was easy and fast, and it worked.

编辑:Alohci的解决方案简单快捷,而且有效。

2 个解决方案

#1


Loop through the .values collection of the HashMap Store the first entry. Compare each remaining entry with the stored one. As soon as you find one that doesn't match, throw your error. If you reach the end of the loop then all the strings match.

循环遍历HashMap Store的.values集合的第一个条目。将每个剩余条目与存储的条目进行比较。一旦找到一个不匹配的,就抛出你的错误。如果到达循环的末尾,则所有字符串都匹配。

#2


It sounds like you need a reverse mapping, that maps all the values to their set of keys.

听起来你需要一个反向映射,它将所有值映射到它们的键集。

Map<Key,Value> forwardMap;
Map<Value, Set<Key> reverseMap;

You can then see if all of the entries you are looking at are in the set. Make sure that you put the reverse mapping in when you add/remove the forward mapping.

然后,您可以查看您正在查看的所有条目是否都在该集合中。添加/删除正向映射时,请确保将反向映射放入其中。

The benefit of this approach, is the test will be O(n) where n is the size of the keys you are testing, and not O(m) where m is the size of the forward map.

这种方法的好处是测试将是O(n),其中n是您正在测试的键的大小,而不是O(m)其中m是前向映射的大小。

#1


Loop through the .values collection of the HashMap Store the first entry. Compare each remaining entry with the stored one. As soon as you find one that doesn't match, throw your error. If you reach the end of the loop then all the strings match.

循环遍历HashMap Store的.values集合的第一个条目。将每个剩余条目与存储的条目进行比较。一旦找到一个不匹配的,就抛出你的错误。如果到达循环的末尾,则所有字符串都匹配。

#2


It sounds like you need a reverse mapping, that maps all the values to their set of keys.

听起来你需要一个反向映射,它将所有值映射到它们的键集。

Map<Key,Value> forwardMap;
Map<Value, Set<Key> reverseMap;

You can then see if all of the entries you are looking at are in the set. Make sure that you put the reverse mapping in when you add/remove the forward mapping.

然后,您可以查看您正在查看的所有条目是否都在该集合中。添加/删除正向映射时,请确保将反向映射放入其中。

The benefit of this approach, is the test will be O(n) where n is the size of the keys you are testing, and not O(m) where m is the size of the forward map.

这种方法的好处是测试将是O(n),其中n是您正在测试的键的大小,而不是O(m)其中m是前向映射的大小。