user10369086
user10369086

Reputation:

How do I find the value of an unknown key in my HashMap and convert it into an int?

Doesnt really need much of an explanation, just wondering what would be the best and efficient way to do that. The HashMap has only one Key left, (checked with map.size() == 1), however the Key is unknown. The HashMap is <Integer, Integer>. Thanks a lot to everyone trying to help!

Upvotes: 0

Views: 1246

Answers (2)

azro
azro

Reputation: 54148

As .keySet() and .entrySet() returns Set you can't direct use a get operation like with List

  1. Through Stream you can :

    int unknowKey = map.keySet().stream()
                                .findAny()
                                .orElseThrow(IllegalArgumentException::new);
    
  2. Or, with Iterator :

    int unknowKey = map.keySet().iterator().next();
    

In term of efficiency, iterator is really superior:

Benchmark         Mode   Cnt    Score    Error   Units
MyBench.iterator  avgt     5   10,663  ± 0,175   ns/op
MyBench.stream    avgt     5   47,960  ± 4,819   ns/op

Upvotes: 2

mettleap
mettleap

Reputation: 1410

Use the keySet method to get the key in a set and then iterate through the set to get the key, like so,

    HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
    map.put(5, 1); // some map with only one key-value pair

    int a = map.keySet().iterator().next(); // obtain keyset, get iterator and get the next element (since you know map size is 1)

    System.out.println(a);

Upvotes: 3

Related Questions