1

I have a TreeMap with entries like

["aftab" = 4, "Manoj" = 5, "Rahul" = 5]

I want to get the key with the max value, but if there are two or more max values I want the key that comes first in the map, Manoj in this case. In My application I used Collections.max(map.getKey()) and it is returning Rahul.

Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110

3 Answers3

1

Make a comparator that sorts the entries by values descending then comparing by keys when two values are equals

Entry.<String, Integer>comparingByValue().reversed()
.thenComparing(Entry.comparingByKey())
Map<String, Integer> map = new TreeMap<>();
map.put("aftab", 4);
map.put("Manoj", 5);
map.put("Rahul", 5);
Entry<String, Integer> result = map.entrySet().stream()
                .sorted(Entry.<String, Integer>comparingByValue().reversed().thenComparing(Entry.comparingByKey()))
                .findFirst().orElseGet(null);

System.out.println(result);

, output

Manoj=5
0xh3xa
  • 4,801
  • 2
  • 14
  • 28
1

Create a Comparator and pass it to Collections.max().

Map<String, Integer> map = new TreeMap<>(
            Map.of("Aftab", 4, "Manoj", 5, "Rahul", 5));

Comparator<Entry<String,Integer>> comp = Entry.comparingByValue();

Entry<String,Integer> e = Collections.max(map.entrySet(),comp);

System.out.println(e);
// or
System.out.println(e.getKey());
WJS
  • 36,363
  • 4
  • 24
  • 39
0

Use Collections::max to find the entry with maximum value from map.entrySet() by using Comparator.comparingInt(Map.Entry::getValue).

Demo:

import java.util.Collections;
import java.util.Comparator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> map = new TreeMap<>();
        map.put("aftab", 4);
        map.put("Manoj", 5);
        map.put("Rahul", 5);

        Entry<String, Integer> entry = Collections.max(map.entrySet(), Comparator.comparingInt(Map.Entry::getValue));
        System.out.println(entry);
    }
}

Output:

Manoj=5
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110