java 将值映射到 ArrayList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36043471/
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
Map values to ArrayList
提问by Hugo Silva
I have a Map<Integer, MyClass>
and MyClass
has 2 fields, Object1 obj
and Object2 objj
for example.
我有一个Map<Integer, MyClass>
和MyClass
有2场,Object1 obj
和Object2 objj
例如。
How can I create an ArrayList<Object2>
with all Object2
values?
我怎样才能创建一个ArrayList<Object2>
具有所有Object2
值的?
Must I iterate the Map
and then add the values to the ArrayList
or exists another way?
我是否必须迭代Map
然后将值添加到ArrayList
或以另一种方式存在?
回答by Paul Boddington
If you are using Java 8 you could do:
如果您使用的是 Java 8,您可以执行以下操作:
List<Object2> list = map.values()
.stream()
.map(v -> v.objj)
.collect(Collectors.toList());
If you are using Java 7 or earlier, the solution of @Marvis the simplest.
回答by Marv
You could iterate over the values of the Map
:
您可以遍历 的值Map
:
ArrayList<Object2> list = new ArrayList<>();
for (MyClass e : map.values()) {
list.add(e.objj);
}
回答by Chirag Parmar
Checkout following :
结帐如下:
How to convert a Map to List in Java?
It has one liner snippet for your question.
它有一个针对您的问题的衬里片段。
List<Object2> list = new ArrayList<Object2>(map.values());
assuming:
假设:
Map<Integer, MyClass> map;