I want to getKey by with duplicate values in map, but the result is not correct, an I have this code for example
import java.util.*;
import java.util.Map.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("A", 10);
map.put("B", 20);
map.put("C", 30);
map.put("D", 10);
map.put("E", 11);
map.put("F", 30);
System.out.println("Before Sorting:");
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
List<Integer> list = new ArrayList<>(map.values());
Collections.sort(list);
Collections.reverse(list);
System.out.println("\nAfter Sorting:");
for (Integer entry : list) {
System.out.println(getKeyByValue(map, entry) + " - " + entry);
}
}
public static <String, Integer> String getKeyByValue(
Map<String, Integer> map, Integer value) {
for (Entry<String, Integer> entry : map.entrySet()) {
if (entry.getValue().equals(value)) {
return entry.getKey();
}
}
return null;
}
}
for now the result of the output is
Before Sorting:
A - 10
B - 20
C - 30
D - 10
E - 11
F - 30
After Sorting:
C - 30
C - 30
B - 20
E - 11
A - 10
A - 10
and the goal is to sort the values in descending order and then get the keys from the values, but since there are duplicate values, I could not get the keys
After Sorting should be:
F - 30
C - 30
B - 20
E - 11
D - 10
A - 10
Any suggestion?