[英]How to get key value pair from a Pojo objects stored in ArrayList using java 7
[英]How to get specific value from ArrayList in POJO in java
Key : 22 Value: Abey
Key : 22 Value : Dawn
Key : 22 Value : Sherry
Key : 22 Value : Sherry
Key : 22 Value : Sherry
我只想用 Sherry 打印 Keys,如何使用 Java 打印?
更改问题标题,因为 HashMap 不存储重复键
HashMap 不接受重复的密钥。 只有重复值。 在您的方法中,您无法存储所显示的所有记录。 例如:
Map<Integer, String> map = new HashMap<>();
map.put(22, "Abey");
map.put(22, "Dawn");
map.put(22, "Sherry");
map.put(22, "Sherry");
map.put(22, "Sherry");
当您打印 HashMap 的 output 时。您只会得到一个 output,因为相同的密钥将替换为最新值。
output:
{22=Sherry}
如果你真的想存储重复键,请在 HashMap 了解更多关于如何存储重复键的信息。
JDK1.8及以上版本可以使用以下方法完成任务。
List<Integer> keys = hashMap.entrySet().stream()
.filter((entry) -> entry.getValue().equals("Sherry"))
.map(entry -> entry.getKey())
.collect(Collectors.toList());
我认为您需要循环遍历 map。没有特定的 function 可以执行此操作
map.forEach((k,val) -> {
if (val.equals("Sherry") {
keys.add(k);
}
});
其中 map 是 HashMap,keys 是一个列表
您可以使用以下代码。
static < K, V > List < K > getAllKeysForValue(Map < K, V > mapOfWords, V value) {
List < K > listOfKeys = null;
//Check if Map contains the given value
if (mapOfWords.containsValue(value)) {
// Create an Empty List
listOfKeys = new ArrayList < > ();
// Iterate over each entry of map using entrySet
for (Map.Entry < K, V > entry: mapOfWords.entrySet()) {
// Check if value matches with given value
if (entry.getValue().equals(value)) {
// Store the key from entry to the list
listOfKeys.add(entry.getKey());
}
}
}
// Return the list of keys whose value matches with given value.
return listOfKeys;
}
也许你可以使用相反的 map,将 Sherry、Dawn 和 Abey 作为键,将 22 作为列表的值。 你可以有这样的东西:
Map<String , Set<String> > reverseMap;
现在你可以在集合中存储像 22这样的密钥,并将这个 map 的密钥作为名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.