java中capitals_Java程序按值对映射进行排序

Java程序按值对映射进行排序

在此程序中,您将学习按Java中的值对给定的映射进行排序。

示例:按值对map排序

import java.util.*;

public class SortMap {

public static void main(String[] args) {

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");

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());

Collections.sort(capitalList, (o1, o2) -> o1.getValue().compareTo(o2.getValue()));

LinkedHashMap result = new LinkedHashMap<>();

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

在上面的程序中,我们将LinkedHashMap国家/地区及其各自的首都,存储在变量capitals中。

我们有一个方法sortMap(),它采用双向链表并返回排序后的双向链表。

在方法内部,我们将哈希映射转换为列表capitalList。然后,我们使用sort()方法,该方法接受一个列表和一个比较器。

在我们的实例中,比较器是将(o1,o2)-> o1.getValue().compareTo(o2.getValue())两个列表o1和o2中的值进行比较的lambda表达式。

运算后,我们得到排序列表capitalList。然后,我们只需将列表转换为LinkedHashMap结果并返回即可。

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值