[英]List of Map entries from map
我正在尝试从地图中获取(按值排序)地图条目列表。 我尝试了这个:
List<Pair<String, AtomicInteger>> expectedList = expectedMap.entrySet().stream()
.sorted(Comparator.comparing(e -> -e.getValue().get()))
.map(e -> new Pair<>(e.getKey(), e.getValue())).collect(Collectors.toList());
但是,如果我尝试用Map.Entry替换Pair,它告诉我Map.Entry是抽象的,无法实例化。 有没有一种方法可以使这种构造获得条目列表而不是对列表?
请参阅Javadoc中的Map.Entry :
接口映射条目
所有已知的实施类:
AbstractMap.SimpleEntry , AbstractMap.SimpleImmutableEntry
例如,选择一个适合您需要的实施类
List<Entry<String, AtomicInteger>> expectedList = expectedMap.entrySet().stream()
.sorted(Comparator.comparingInt(e -> -e.getValue().get()))
.map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue()))
.collect(Collectors.toList());
但是,您也可以只删除map
并使用entrySet()
返回的条目:
List<Entry<String, AtomicInteger>> expectedList = expectedMap.entrySet().stream()
.sorted(Comparator.comparingInt(e -> -e.getValue().get()))
.collect(Collectors.toList());
PS .:如果要比较原始数据类型,则应使用正确的方法,例如comparingInt
。 这样可以避免不必要的装箱。
我不明白为什么你需要映射Map.Entry
给别人,如果你需要的东西Map.Entry
。
这是我的看法。 我选择先创建一个条目列表,然后对其进行排序。 还使用mor的内置API来构造比较器。
List<Map.Entry<String, AtomicInteger>> expectedList =
new ArrayList<>(expectedMap.entrySet());
Collections.sort(expectedList,
Map.Entry.comparingByValue(
Comparator.comparingInt(AtomicInteger::get).reversed());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.