TreeMap 到 ArrayList Java
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20539831/
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
TreeMap to ArrayList Java
提问by User3
I have a TreeMap which has a string key and the value part is a List with atleast four values.
我有一个 TreeMap ,它有一个字符串键,值部分是一个至少有四个值的列表。
Map<String,List<String>> mMap = new TreeMap<String,List<String>>();
I am using the tree map so that my keys are sorted. However after the sort I want to map this TreeMap to a listview. I want to convert the Map to a list and then build an Adapter for listview. However I am not able to convert it when I do
我正在使用树图以便对我的键进行排序。但是排序后我想将此 TreeMap 映射到列表视图。我想将 Map 转换为列表,然后为列表视图构建一个适配器。但是当我这样做时我无法转换它
ArrayList<String> trendyList = new ArrayList<String>(mMap);
It says: The constructor ArrayList<String>(Map<String,List<String>>) is undefined
它说: The constructor ArrayList<String>(Map<String,List<String>>) is undefined
Is there any other way I can do this?
有没有其他方法可以做到这一点?
采纳答案by Tim B
Assuming you want a list of list of strings:
假设您想要一个字符串列表列表:
List<List<String>> trendyList = new ArrayList<>(mMap.values());
If you want to merge the lists then it becomes a bit more complex, you would need to run through the values yourself and do the merge.
如果你想合并列表,那么它会变得有点复杂,你需要自己运行这些值并进行合并。
To merge the lists:
要合并列表:
List<String> trendyList = new ArrayList<>();
for (List<String> s: mMap.values()) {
trendyList.addAll(s);
}
To merge the lists with keys:
将列表与键合并:
List<String> trendyList = new ArrayList<>();
for (Entry<String, List<String>> e: mMap.entrySet()) {
trendyList.add(e.getKey());
trendyList.addAll(e.getValue());
}
In Java 8 you get new tools for doing this.
在 Java 8 中,您可以获得用于执行此操作的新工具。
To merge the lists:
要合并列表:
// Flat map replaces one item in the stream with multiple items
List<String> trendyList = mMap.values().stream().flatMap(List::stream).collect(Collectors.toList())
To merge the lists with keys:
将列表与键合并:
List<String> trendyList = mMap.entrySet().stream().flatMap(e->Stream.concat(Stream.of(e.getKey()), e.getValue().stream()).collect(Collectors.toList());
回答by Jens Baitinger
A Map can be seen as a colleciton of key-value pairs, a list is just a collection of values. You have to choose if you now want your keys, then you use keySet()
or if you want your values than you use values()
wich returns a collection of List<String>
Map 可以看作是键值对的集合,列表只是值的集合。你必须选择你现在是否想要你的密钥,然后你使用keySet()
或者你想要你的值而不是你使用的values()
返回一个集合List<String>