java Java8 将对象列表转换为对象的一个​​属性列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42305543/
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 06:31:56  来源:igfitidea点击:

Java8 Transform list of object to list of one attribute of object

javalistlambdajava-8java-stream

提问by Nik

I want to use Java 8 tricks to do the following in one line.

我想使用 Java 8 技巧在一行中执行以下操作。

Given this object definition:

鉴于此对象定义:

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class MyObj {
    private String id;
    private Double value;
}

and a List<MyObj> objects, I want to get a List<String> objectIdswhich is a list of all ids of the objects in the first list - in the same order.

和 a List<MyObj> objects,我想得到 a List<String> objectIds,它是第一个列表中所有id对象的列表 - 以相同的顺序。

I can do this using a loop in Java but I believe there should be a one-liner lambda in Java8 that can do this. I was not able to find a solution online. Perhaps I wasn't using the right search terms.

我可以使用 Java 中的循环来做到这一点,但我相信 Java8 中应该有一个单行 lambda 可以做到这一点。我无法在网上找到解决方案。也许我没有使用正确的搜索词。

Could someone suggest a lambda or another one-liner for this transform?

有人可以为这个转换建议一个 lambda 或另一个单行吗?

回答by xiumeteo

This should do the trick:

这应该可以解决问题:

objects.stream().map(MyObj::getId).collect(Collectors.toList());

objects.stream().map(MyObj::getId).collect(Collectors.toList());

that said, the method reference::operator allows you to reference any method in your classpath and use it as a lambda for the operation that you need.

也就是说,方法引用::运算符允许您引用类路径中的任何方法,并将其用作所需操作的 lambda。

As mentioned in the comments, a stream preserves order.

正如评论中提到的,流会保留顺序。