按值对 Map 进行排序的 Java 程序
要理解此示例,您应该具备以下 Java 编程的知识:
示例:按值对 Map 进行排序
import java.util.*;
public class Main {
public static void main(String[] args) {
// create a map and store elements to it
LinkedHashMap 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");
// call the sortMap() method to sort the map
Map result = sortMap(capitals);
for (Map.Entry entry : result.entrySet()) {
System.out.print("Key: " + entry.getKey());
System.out.println(" Value: " + entry.getValue());
}
}
public static LinkedHashMap sortMap(LinkedHashMap map) {
List capitalList = new LinkedList(map.entrySet());
// call the sort() method of Collections
Collections.sort(capitalList, (l1, l2) -> l1.getValue().compareTo(l2.getValue()));
// create a new map
LinkedHashMap result = new LinkedHashMap();
// get entry from list to the map
for (Map.Entry 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
在上面的程序中,我们创建了一个名为 capitals
的 LinkedHashMap
。 该 Map 存储国家及其各自的首都。
在这里,我们创建了一个获取 Map
并返回排序后的 Map
的 sortMap()
方法。
在方法内部,我们首先从 Map capitals
上创建了一个名为 capitalList
, 然后我们使用 Collections
的 sort()
方法对 capitalList
列表的元素进行排序。
该 sort()
方法有两个参数:要排序的列表和一个比较器。在我们的例子中,比较器是一个 lambda 表达式。
(l1, l2) -> l1.getValue().compareTo(l2.getValue())
这里,lambda 表达式采用列表中的两个相邻的元素 (l1
和 l2
) 。然后使用 getValue()
方法获取值并使用 compareTo()
两个值的。
操作后,我们得到排序后的列表 capitalList
. 然后,我们只需将列表转换为名为 result
的 LinkedHashMap
并将其归还。
回到 main()
方法中,我们遍历 Map 中的每个项目并打印其键和值。