我正在创建一个链接的HashMap,它将从用户输入中读取一个字符串和整数。设置如下:
LinkedHashMap<String, Integer> wordIndex = new LinkedHashMap<String, Integer>();
我的目标是删除用户可能输入的所有重复项。这是一个示例:
wordIndex.put("The", 0);
wordIndex.put("Hello", 6);
wordIndex.put("Katherine", 17);
wordIndex.put("Hello", 21);
我要保留第一个“ Hello”并删除第二个。
这是我第一次使用Linked HashMaps,因此,我对自己可以使用的内置函数不熟悉。是否有HashMaps的功能,可让我每次输入新的值和键时逐一检查wordIndex HashMap以查找重复项?如果没有,我可以使用什么过程来单独检查重复项?谢谢您的帮助。
答案 0 :(得分:2)
默认行为将Override
与现有key
的现有值一起使用,因此LinkedHashMap中具有以下值
{The=0, Hello=21, Katherine=17}
,然后您可以使用key
containsKey()
是否已经存在。
if (wordIndex.containsKey("Hello")) {
// do something
}
答案 1 :(得分:2)
您说:
我要保留第一个“你好”并删除第二个。
要防止第二个条目尝试覆盖Map
中的第一个条目,请在Java 8及更高版本中使用Map::putIfAbsent
。
Map<String, Integer> wordIndex = new LinkedHashMap<>();
wordIndex.putIfAbsent("The", 0);
wordIndex.putIfAbsent("Hello", 6);
wordIndex.putIfAbsent("Katherine", 17);
wordIndex.putIfAbsent("Hello", 21);
wordIndex.entrySet().forEach(System.out::println);
打印
The=0
Hello=6
Katherine=17
Map.putIfAbsent
仅保留输入的第一个值。我们可以看到第一个("Hello", 6)
条目仍然存在,而第二个("Hello", 21)
条目尝试失败并被丢弃。