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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 00:54:55  来源:igfitidea点击:

Map values to ArrayList

javadictionaryarraylist

提问by Hugo Silva

I have a Map<Integer, MyClass>and MyClasshas 2 fields, Object1 objand Object2 objjfor example.

我有一个Map<Integer, MyClass>MyClass有2场,Object1 objObject2 objj例如。

How can I create an ArrayList<Object2>with all Object2values?

我怎样才能创建一个ArrayList<Object2>具有所有Object2值的?

Must I iterate the Mapand then add the values to the ArrayListor 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.

如果您使用的是 Java 7 或更早版本,@Marv解决方案是最简单的。

回答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?

如何在 Java 中将地图转换为列表?

It has one liner snippet for your question.

它有一个针对您的问题的衬里片段。

List<Object2> list = new ArrayList<Object2>(map.values());

assuming:

假设:

Map<Integer, MyClass> map;