跳到主要内容

Java 程序:根据值对 Map 进行排序

要理解此示例,您应该具备以下 Java 编程 主题的知识:

示例:按值对 Map 进行排序

import java.util.*;
import java.util.Map.Entry;

class Main {

public static void main(String[] args) {

// 创建一个 map 并向其中添加元素
LinkedHashMap<String, String> capitals = new LinkedHashMap<>();
capitals.put("Nepal", "Kathmandu");
capitals.put("India", "New Delhi");
capitals.put("United States", "Washington");
capitals.put("England", "London");
capitals.put("Australia", "Canberra");

// 调用 sortMap() 方法对 map 进行排序
Map<String, String> result = sortMap(capitals);

for (Map.Entry<String, String> entry : result.entrySet()) {
System.out.print("Key: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}

public static LinkedHashMap<String, String> sortMap(LinkedHashMap<String, String> map) {
List<Entry<String, String>> capitalList = new LinkedList<>(map.entrySet());

// 调用 Collections 的 sort() 方法
Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue()));

// 创建一个新的 map
LinkedHashMap<String, String> result = new LinkedHashMap<>();

// 将列表中的条目添加到 map 中
for (Map.Entry<String, String> entry : capitalList) {
result.put(entry.getKey(), entry.getValue());
}

return result;
}
}

输出

Key: Australia Value: Canberra
Key: Nepal Value: Kathmandu
Key: England Value: London
Key: India Value: New Delhi
Key: United States Value: Washington

在上面的程序中,我们创建了一个名为 capitalsLinkedHashMap。这个 map 存储了国家及其对应的首都。

这里,我们创建了一个 sortMap() 方法,该方法接收一个 map 并返回排序后的 map。

在该方法内部,我们首先从 capitals map 创建了一个名为 capitalList 的列表。然后我们使用 Collectionssort() 方法对列表元素进行排序。

sort() 方法接受两个参数:要排序的列表一个比较器。在我们的例子中,比较器是一个 lambda 表达式。

(l1, l2) -> l1.getValue().compareTo(l2.getValue())

在这里,lambda 表达式接受列表中两个相邻的元素(l1l2)。它使用 getValue() 方法获取值,并使用 compareTo() 方法比较两个值。

操作完成后,我们获得了排序后的列表 capitalList。然后,我们简单地将列表转换为名为 resultLinkedHashMap 并返回它。

回到 main() 方法中,我们遍历 map 中的每个项并打印其键和值。