Forgive me if it seems simple but I couldn't figure it out easily. I thought about using a loop but was wondering if anybody knows an easier way: I have:
Map<String, Integer> map = new HashMap<>();
map.put("ClubB", 1);
map.put("ClubA", 2);
map.put("ClubC", 2);
map.put("ClubD", 2);
map.put("ClubE", 3);
map.put("ClubF", 2);
map.put("ClubG", 2);
I need to get keys or values at specific index in my tests. For example I need to get the key and value at index 3 etc. The reason is that I use a comparator and sort the Map and would like to show that the value at a specific index has changed.
Thanks for any ideas.
UPDATE:
I used:
HashMap leagueTable = new HashMap();
Map<String, Integer> map = sortByValues(leagueTable);
public <K extends Comparable<K>, V extends Comparable<V>> Map<K, V> sortByValues(final Map<K, V> map) {
Comparator<K> valueComparator = new Comparator<K>() {
public int compare(K k1, K k2) {
int compare = map.get(k2).compareTo(map.get(k1));
if (compare == 0) {
return k1.compareTo(k2); // <- To sort alphabetically
} else {
return compare;
}
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
I then used aloop to print out values:
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println( entry.getKey() + ", " + entry.getValue() );
}