For the reverse order switch o2 and o1 . To get the first element, simply access the array with index 0:
Map<String, Integer> map = new HashMap<>(); map.put("a", 4); map.put("c", 6); map.put("b", 2); Object[] a = map.entrySet().toArray(); Arrays.sort(a, new Comparator() { public int compare(Object o1, Object o2) { return ((Map.Entry<String, Integer>) o1).getValue().compareTo( ((Map.Entry<String, Integer>) o2).getValue()); } }); for (Object e : a) { System.out.println(((Map.Entry<String, Integer>) e).getKey() + " : " + ((Map.Entry<String, Integer>) e).getValue()); } System.out.println("first element is " + ((Map.Entry<String, Integer>) a[0]).getKey() + " : " + ((Map.Entry<String, Integer>) a[0]).getValue());
What seal
b: 2
a: 4
c: 6
the first element is b: 2
If you have access to a lambda expression, you can simplify sorting with the following:
Arrays.sort(a, (o1, o2) -> ((Map.Entry<String, Integer>) o1).getValue().compareTo(((Map.Entry<String, Integer>) o2).getValue()));
source share