Search code examples
javajava-streamlinkedhashmap

Get first LinkedHashMap key with a given value


I use the following LinkedHashMap and get the occurences of numbers as <number, occurences>.

Map<Integer, Integer> map = new LinkedHashMap<>();

The values stored in the map are as in the following:

key | value
4   | 2
10  | 2
5   | 1
3   | 1

I want to get the first key that has value of 1 (in the example, it is 5). If there is not a key that has value of 1, it returns -1. I use the following approach, but I think it is not a proper way and there may be a better or short way to do this:

int key = map.containsValue(1) ?
                map.entrySet().stream()
                   .filter(entry -> entry.getValue() == 1)
                   .map(Map.Entry::getKey).findFirst().get() : -1;

Is there a better way to achieve this?


Solution

  • Rather than checking containsValue first, use orElse on the optional returned by findFirst, which is one fewer iteration through the map.

    int key = map.entrySet().stream()
                   .filter(entry -> entry.getValue() == 1)
                   .map(Map.Entry::getKey).findFirst().orElse(-1);
    

    findFirst would return an empty optional if there is nothing left after the filter. This only happens if there is no value 1 in the map to begin with. orElse returns its argument, if the optional is empty, otherwise it returns the wrapped value.