我有一个我正在简化的地图,但在本质中包含一些数据的关键值,例如:
Yahya, 4
John, 4
Blake, 2
Jill 2
Janoe, 6
Jilly 12
Zapon, 5
Zoe, 4
Hamed, 1
我需要订购这个,以便得到以下输出:
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
我已经使用比较器根据值来排序Map值:
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;
}
并阅读:How to get element position from Java Map,Order HashMap alphabetically by value等等,但不确定如何将它放在一起。
我知道你可以用它来获取关键值:
for (Map.Entry<String, Integer> entry : map.entrySet()){
System.out.println(entry.getKey() + " ," + entry.getValue() + " pts");
}
但缺少两个功能:
试过这个:
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++;
}
任何想法都表示赞赏和欢迎。任何人都可以提出一种方法来达到要求的结果吗?
答案 0 :(得分:0)
ValueComparator
替换if (compare == 0) return 1;
if(compare == 0) return k1.compareTo(k2)
。答案 1 :(得分:0)
这就是我最终要做的就是让正确的计数器工作:
<td>$-12.75</td>