[英]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
I want to print only Keys with Sherry only,how to do it using Java?我只想用 Sherry 打印 Keys,如何使用 Java 打印?
Changing title of question because HashMap doesn't store duplicate Keys更改问题标题,因为 HashMap 不存储重复键
HashMap doesn't accept duplicate keys. HashMap 不接受重复的密钥。 Only duplicate values.
只有重复值。 In your approach you can't be able to store all the records as you are showing.
在您的方法中,您无法存储所显示的所有记录。 for example:
例如:
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");
when you print the output of the HashMap. You only get one output because the same key will replace to latest value.当您打印 HashMap 的 output 时。您只会得到一个 output,因为相同的密钥将替换为最新值。
output: output:
{22=Sherry}
If you really want to store duplicate keys, Learn more about how to store duplicate keys in HashMap.如果你真的想存储重复键,请在 HashMap 了解更多关于如何存储重复键的信息。
You can use the below method from JDK1.8 and above to complete the task. JDK1.8及以上版本可以使用以下方法完成任务。
List<Integer> keys = hashMap.entrySet().stream()
.filter((entry) -> entry.getValue().equals("Sherry"))
.map(entry -> entry.getKey())
.collect(Collectors.toList());
I think you need to loop through the map. There is no specific function to do this我认为您需要循环遍历 map。没有特定的 function 可以执行此操作
map.forEach((k,val) -> {
if (val.equals("Sherry") {
keys.add(k);
}
});
where map is the HashMap and keys is a list其中 map 是 HashMap,keys 是一个列表
You can use the following code.您可以使用以下代码。
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;
}
Maybe you can use the reverse map, having Sherry, Dawn and Abey as keys, and 22 as the value of list.也许你可以使用相反的 map,将 Sherry、Dawn 和 Abey 作为键,将 22 作为列表的值。 You can have something like:
你可以有这样的东西:
Map<String , Set<String> > reverseMap;
Now you can store the keys like 22 in the set and have the key of this map as the name.现在你可以在集合中存储像 22这样的密钥,并将这个 map 的密钥作为名称。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.