dayao
dayao

Reputation: 9

How to get the specific <K,V> entry based on the given key in Java HashMap?

Ex. I have the following HashMap, and how to get the entry 'b'=6 if I know the key 'b'. Is there any way to do it?

Map<Character, Integer> map=new HashMap<>();
map.put('a',7);
map.put('b',6);
map.put('c',5);`

By the way, I want to do this is because all those entries are in a priority queue. I have to remove that entry from the priority queue and re-insert it to make sure it is in order.

Thanks.

Upvotes: 0

Views: 938

Answers (3)

Giorgi Tsiklauri
Giorgi Tsiklauri

Reputation: 11138

Since Java 9, you can use static method Map.entry​(K k, V v), which:

returns an unmodifiable Map.Entry containing the given key and value.

So, you can obtain your Entry<K, V> instance, as:

Map.Entry<Character, Integer> entry = Map.entry(key, map.get(key));

where map stores a reference to your Map<K, V> instance.

Upvotes: 0

Nikolas
Nikolas

Reputation: 44486

If you know the key, simply get the value using Map#get(Object). As long as you know both, you have the entry. The Map interface doesn't provide a specific method that returns a certain entry.

Map<Character, Integer> map = ...
Character key = 'b';
Integer value = map.get(key);

// now with the 'key' and 'value' that make TOGETHER an entry.

If you really somehow need an Entry<Character, Integer> construct it like this:

Map.Entry<Character, Integer> entry = new SimpleEntry<>(key, value);

There is no better way. One would say you can use Stream API to iterate through the entries and return the first one found, however, you lose the main benefit of the HashMap which is the constant-time look-up.

// DON'T DO THIS!

Entry<Character, Integer> entry = map.entrySet().stream()
        .filter(e -> key.equals(e.getKey()))
        .findFirst()
        .orElse(null);

Upvotes: 2

You could do something like this

public Entry<Character, Integer> entry_return(Map<Character, Integer> map) {
    for(Map.Entry<Character, Integer> entry : map.entrySet()) {
        if(entry.getKey() == 'b')
            return entry;
    }
}

or use a stream API if you really need the entry but i don't know if that is very common/usefull

Upvotes: 0

Related Questions