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中的每个项目并打印其键和值。