我有以下HashMap<String,Integer>
使用 Comparator
根据值按降序排序
Collections.sort(entryList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> entry1, Entry<String, Integer> entry2) {
// TODO Auto-generated method stub
return entry2.getValue().compareTo(entry1.getValue());
}
b=3, cococ=2, 5005=1, p=1, sees=1, k=1, dad=1, pip=1, peep=1
我现在想按字典顺序对该映射中的条目进行排序,前提是值相同(本例中为值 1)
b=3 cococ=2 5005 = 1 dad = 1 k = 1 peep = 1 p = 1 pip=1 sees=1
我该怎么做?
最佳答案
您需要使用双重标准对 map 进行排序,首先检查键是否相同,然后按键排序...
public int compare(Entry<String, Integer> entry1, Entry<String, Integer> entry2) {
int ret = entry2.getValue().compareTo(entry1.getValue());
if (ret == 0) {// if 0 the are the same then compare the keys
return entry1.getKey().compareTo(entry2.getKey());
}
return ret;
}
关于java - HashMap字典顺序java如果值相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40690803/