简体   繁体   中英

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?

Changing title of question because HashMap doesn't store duplicate Keys

HashMap doesn't accept duplicate keys. 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.

output:

{22=Sherry}

If you really want to store duplicate keys, Learn more about how to store duplicate keys in HashMap.

You can use the below method from JDK1.8 and above to complete the task.

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.forEach((k,val) -> {
  if (val.equals("Sherry") {
    keys.add(k);
  }
});

where map is the HashMap and keys is a list

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM