比较 Java 中现有的数据条目

发布于 2024-07-10 19:26:21 字数 244 浏览 6 评论 0原文

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

示例:假设我有 4 个字符串,如果可能的话,我打算相互比较,但其中只有 3 个最终出现在 HashMap 中。 如何比较存在的字符串而不尝试将它们与不存在的字符串进行比较,并且不执行一堆嵌套的 if 和 else?

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

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.

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?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

妄司 2024-07-17 19:26:21

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

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.

情场扛把子 2024-07-17 19:26:21

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

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

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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文