我有一个简单的 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。在想:
- 创建另一个 map 然后遍历列表
- 从第一张 map 获取号码
- 将数字作为键,将名称作为新映射中的值
- 按键排序 map
- 迭代抛出新映射然后将值添加到列表
这看起来很糟糕:/,有什么建议和更好的数据结构可以使用吗?
最佳答案
使用 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/