要按值对HashMap进行排序并转换为新的Map,可以按照以下步骤进行操作:
下面是一个Java代码示例:
import java.util.*;
public class HashMapSortByValue {
public static void main(String[] args) {
// 创建一个HashMap并添加键值对
HashMap hashMap = new HashMap<>();
hashMap.put("A", 5);
hashMap.put("B", 3);
hashMap.put("C", 9);
hashMap.put("D", 1);
hashMap.put("E", 7);
// 调用sortByValue方法进行排序并转换为新的Map
Map sortedMap = sortByValue(hashMap);
// 打印排序后的Map
for (Map.Entry entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
public static Map sortByValue(HashMap hashMap) {
// 创建一个ArrayList来存储HashMap的条目
ArrayList> list = new ArrayList<>(hashMap.entrySet());
// 使用Collections的sort方法对ArrayList进行排序
Collections.sort(list, new Comparator>() {
@Override
public int compare(Map.Entry o1, Map.Entry o2) {
// 按值进行排序,如果要按降序排序,可以将o1和o2的位置调换
return o1.getValue().compareTo(o2.getValue());
}
});
// 创建一个新的LinkedHashMap来存储排序后的条目
LinkedHashMap sortedMap = new LinkedHashMap<>();
for (Map.Entry entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
return sortedMap;
}
}
运行上述代码,输出将会是按值排序后的新Map:
D: 1
B: 3
A: 5
E: 7
C: 9