Java 如何将哈希映射键转换为列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31820049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert hash map keys into list?
提问by Jay
I have a hash map and I'm trying to convert the keys to a list. Here's the code:
我有一个哈希映射,我正在尝试将键转换为列表。这是代码:
List<ARecord> recs = new ArrayList<ARecord>();
HashMap<String, ARecord> uniqueRecs = new HashMap<String, ARecord>();
for(ARecord records:recs){
if(!uniqueRecs.containsKey(records.getId())){
uniqueRecs.put(records.getId(), records);
}
}
When I try to do
当我尝试做
List<ARecord> finalRecs = new ArrayList<ARecord>(uniqueRecs.keySet());
The error:
错误:
The constructor ArrayList(Set) is undefined".
构造函数 ArrayList(Set) 未定义”。
How can I convert Hashmap keys to List<ARecord>
finalRecs?
如何将 Hashmap 键转换为List<ARecord>
finalRecs?
回答by schtever
The following works under Java 1.7 and 1.8:
以下适用于 Java 1.7 和 1.8:
List<ARecord> finalRecs = new ArrayList<ARecord>();
for (final String key : uniqueRecs.keySet()) {
finalRec.add(new ARecord() {
public String gettld() {
return key;
}
});
}
回答by ka4eli
Your uniqueRecs
has String
type of the key. You have to do:
你uniqueRecs
有String
钥匙的类型。你必须要做:
List<String> keys = new ArrayList<>(uniqueRecs.keySet());
or
或者
List<ARecord> values = new ArrayList<>(uniqueRecs.values());
回答by Martin De Simone
What worked for me that i wanted to modify an existing list was:
我想修改现有列表对我有用的是:
list.addAll(map.keySet());
回答by Martin Meeser
I think the best way to do this 'nowadays' is:
我认为“现在”做到这一点的最佳方法是:
List<Integer> result = map.keySet().stream().collect(Collectors.toList());
This will notthrow any warnings and will get the List<Integer>
generic correctly.
这不会抛出任何警告,并将List<Integer>
正确获取泛型。