Java8将对象列表转换为对象的一个​​属性列表 [英] Java8 Transform list of object to list of one attribute of object

查看:206
本文介绍了Java8将对象列表转换为对象的一个​​属性列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

给定此对象定义:

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

列表< MyObj>对象,我想要一个 List< String> objectIds 这是第一个列表中对象的所有 id 的列表 - 按相同的顺序排列。

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

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

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.

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

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

推荐答案

这应该可以解决问题:

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

表示方法参考 :: 运算符允许您引用类路径中的任何方法,并将其用作lambda以进行所需的操作。

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.

正如评论中所提到的,流保留了订单。

As mentioned in the comments, a stream preserves order.

这篇关于Java8将对象列表转换为对象的一个​​属性列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆