Java 程序:按值对 Map 进行排序

要理解此示例,您应了解以下Java编程主题


示例:按值对Map进行排序

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

class Main {

  public static void main(String[] args) {

    // create a map and store elements to it
    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");

    // call the sortMap() method to sort the map
    Map<String, String> 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 <Entry<String, String>> 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<String, String> result = new LinkedHashMap();

    // get entry from list to the 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。

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

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

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

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

操作完成后,我们得到排序后的列表 capitalList。然后,我们只需将列表转换为名为 resultLinkedHashMap 并返回它。

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

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战