[英]How do I create a List<Map.Entry<String, Integer>> out of a Map<String, Integer>?
So I know how to create a List of Map values new ArrayList<String, Integer>(map.getValues());
所以我知道如何创建 Map 值的列表
new ArrayList<String, Integer>(map.getValues());
Or from entry set map.entrySet()
However there doesn't seem to be a similar way to add a list of Map.Entry<String, Integer> Is there a way to do this so I can write it all in just a return statement?或者从条目集
map.entrySet()
但是似乎没有类似的方法来添加 Map.Entry<String, Integer> 的列表有没有办法做到这一点所以我可以把它全部写下来陈述?
Map<String, Integer> map = new TreeMap<String, Integer>();
public List<Map.Entry<String, Integer>> getWordList(){
return new ArrayList<Map.Entry<String, Integer>>(map);
}
This doesn't work.这是行不通的。 But what does?
但是呢?
entrySet
returns a Set
and not a List
, which means that the map's keys may or may not be in order. entrySet
返回一个Set
而不是List
,这意味着地图的键可能有序也可能不有序。
However, in the case of TreeMap
the JavaDoc says the following about it:然而,在
TreeMap
的情况下, JavaDoc 说了以下内容:
Returns a
Set
view of the mappings contained in this map.返回此 map 中包含的映射的
Set
视图。The set's iterator returns the entries in ascending key order.
该集合的迭代器以升序键顺序返回条目。
Apparently, entrySet()
guarantees the mappings to be in the same order as the TreeMap
.显然,
entrySet()
保证映射与TreeMap
的顺序相同。 In short, you could just use it anywhere where a Collection
is required.简而言之,您可以在需要
Collection
的任何地方使用它。 Creating a List
is then trivial:创建一个
List
就很简单了:
new ArrayList<>(map.entrySet())
or或者
List.copyOf(map.entrySet())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.