'Get first LinkedHashMap key based on value in Java

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;

So, is there a better way to achieve this?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source