我使用 <String,Integer>
的映射、姓名(唯一)和年级。
我进行了排序,因此最高等级排在第一位(及其键值)。
但是,如果两个成绩相同,我需要按字母顺序打印它们。
到目前为止,我得到了这个,它按值降序排列:
public <String, Integer extends Comparable<? super Integer>> Map<String, Integer> sortByValue(Map<String, Integer> map) {
List<Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
list.sort(Entry.comparingByValue());
//actually need descending order, so use comparator to change from natural ordering
Comparator comparator = Collections.reverseOrder();
list.sort(Entry.comparingByValue(comparator));
Map<String, Integer> result = new LinkedHashMap<>();
for (Entry<String, Integer> entry : list) {
result.put(entry.getKey(), entry.getValue());
}
return results;
}
我尝试通过复制到 ArrayList 来工作,尽管我感觉走进了死胡同:
List<String> listnames = new ArrayList<>();
for(String names : result.keySet()){
listnames.add(names);
}
List<Integer> listgrades = new ArrayList<>();
for(Integer grades : result.values()){
listgrades.add(grades);
}
for (int i = 0 ; i<result.size() ; i ++){
if(listgrades.get(i).equals(listgrades.get(i+1))){
result.get(listgrades.);
//.....
}
}
任何帮助/提示表示赞赏!
最佳答案
您可以同时按两个属性排序:
Comparator<Entry<String, Integer>> comparator = Comparator.comparing(Entry::getValue);
Comparator<Entry<String, Integer>> comparator2 = comparator.reversed(); // Here sort the grade in reversed order (highest come first)
Map<String, Integer> sortedMap = map.entrySet().stream()
.sorted(comparator2.thenComparing(Entry::getKey))
.collect(toMap(Entry::getKey, Entry::getValue,
(v1, v2) -> v2, LinkedHashMap::new));
引入 Map
让事情变得更加复杂.
您可以对 List<Student>
执行相同的操作哪里Student {name; grade}
关于java - 交换 HashMap 中特定的<key,value>集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50432499/