I have a Map which I am simplifying but in essense contains key values of some data such as:
Yahya, 4
John, 4
Blake, 2
Jill 2
Janoe, 6
Jilly 12
Zapon, 5
Zoe, 4
Hamed, 1
I need to order this so that I get the following output:
1. Jilly, 12 pts
2. Janoe, 6 pts
3. Zapon, 5 pts
4. John, 4 pts
4. Yahya, 4 pts
4. Zoe, 4 pts
7. Blake, 2 pts
7. Jill, 2 pts
9. Hamed, 1 pts
I have already used a comparator to order the Map values according to value:
public <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 1;
else return compare;
}
};
Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
sortedByValues.putAll(map);
return sortedByValues;
}
and read : How to get element position from Java Map, Order HashMap alphabetically by value and much more but not sure how to put it together.
I know you can use this to get key values:
for (Map.Entry<String, Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + " ," + entry.getValue() + " pts");
}
However two functionalities missing:
- Sort alphabetically when keys are the same
- Keep same numbering when the value is the same and jump to correct count afterwards.
Tried this:
Map<String, Integer> map = sortByValues(groupList);
int count = 1;
int counter = 1;
int previousScore = 0;
for (Map.Entry<String, Integer> entry : map.entrySet()) {
//counter = count;
if (previousScore == entry.getValue()) {
System.out.println(counter - 1 + " " + entry.getKey() + "," + entry.getValue() + " pts");
} else {
System.out.println(counter + " " + entry.getKey() + "," + entry.getValue() + " pts");
previousScore = entry.getValue();
count++;
}
counter++;
}
Any thoughts are appreciated and welcome. Can anybody suggest a method to achieve the required result ?