0

I have a Treemap with some values, i.e.

TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
map.put(1,7);
map.put(6,3);  
map.put(3,18);
map.put(7,2);
map.put(12,42);

How do I get the ID (12) by searching for the highest value(42) looking through the values of the map?

  • 2
    You'll need to iterate through all the entries. If you want to search keys by values, you'd better reverse your map, because a map is useful to search values by keys. – JB Nizet Mar 31 '19 at 17:38

1 Answers1

2

We can get the entrySet() from the TreeMap and stream on it, then find the max value from the set of entries by comparing the values of each entries and getting the key from the entry having the highest value.

map.entrySet().stream()
              .max(Map.Entry.comparingByValue()))
              .ifPresent(e -> System.out.println(e.getKey()));
Fullstack Guy
  • 16,368
  • 3
  • 29
  • 44