java - 根据 map 中的优先级对列表进行排序

标签 java data-structures

我有一个简单的 map ,需要创建一个列表,该列表根据给定列表中的数字按升序排序:

Map auto = new HashMap();
auto.put("Merc", 3);
auto.put("Citroen", 5);
auto.put("Opel", 10);
auto.put("BMW", 20);

List<String> given = new ArrayList<>();
given.add("Opel");
given.add("BMW");
given.add("Citroen");

因此需要对给定列表进行排序,以便按以下顺序排列:Citroen、Opel、BMW。在想:

  1. 创建另一个 map 然后遍历列表
  2. 从第一张 map 获取号码
  3. 将数字作为键,将名称作为新映射中的值
  4. 按键排序 map
  5. 迭代抛出新映射然后将值添加到列表

这看起来很糟糕:/,有什么建议和更好的数据结构可以使用吗?

最佳答案

使用 Java 8 你可以做到。

Map<String, Integer> auto = new HashMap<>();
auto.put("Merc", 3);
auto.put("Citroen", 5);
auto.put("Opel", 10);
auto.put("BMW", 20);

List<String> given = new ArrayList<>();
given.add("Opel");
given.add("BMW");
given.add("Citroen");

// to sort the selected elements.
given.sort(Comparator.comparing(auto::get));

// to sort all elements.
List<String> names = auto.entrySet().stream()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());

打破这个

List<String> names = 
         // give the set of entries as a Stream.
         auto.entrySet().stream()
        // sort these entries, using the field returned by getValue()
        .sorted(Comparator.comparing(Map.Entry::getValue))
        // now sorted, turn each Entry into just the getKey()
        .map(Map.Entry::getKey)
        // now we have a stream of keys, turn this into a List<String>
        .collect(Collectors.toList());

关于java - 根据 map 中的优先级对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25371300/

相关文章:

java - 如何有效地搜索 HashMap 中所有值的子字符串?

java - 简单的 for 语句不会继续循环?

java - 作为 if 语句的结果,如何在另一个 react 流中使用一个 react 流

链表中的损坏指针

c++ - C++ 中的 AVL 树

java - 创建自定义列表数据结构时可能出现逻辑错误

c++ - 哪种数据结构最适合这个?

java - 在android TextView中格式化长段落

java - 将ejb代码更改为EntityManager代码

java - Desktop Java 类的窗口位置和大小