Home > Software engineering >  Get first LinkedHashMap key based on value in Java
Get first LinkedHashMap key based on value in Java

Time:05-24

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?

CodePudding user response:

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.

CodePudding user response:

  1. Swap key, value (prepare): Map<Integer, List<Integer>> swapped = map.entrySet() .stream() .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
  2. Get value: swapped.containsKey(1) ? swapped.get(1).get(0) : -1;
  • Related