将对象属性列表加入String [英] Join a list of object's properties into a String

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

问题描述

我现在正在学习lambda,我想知道如何用lambda一行编写这段代码。

I'm learning lambda right now, and I wonder how can I write this code by a single line with lambda.

我有一个类,其中包含 ID 名称字段

I have a Person class which includes an ID and name fields

目前,我有一个 List< Person> ,它存储了这些 Person 对象。我想要完成的是获得一个由人的ID组成的字符串就像。

Currently, I have a List<Person> which stores these Person objects. What I want to accomplish is to get a string consisting of person's id just like.

id1,id2,id3

如何使用lambda完成此操作?

How can I accomplish this with lambda?

推荐答案

要检索一个字符串包含由分隔符分隔的所有ID 首先必须 映射 Person ID添加到新流中,然后可以应用 Collectors.joining on。

To retrieve a String consisting of all the ID's separated by the delimiter "," you first have to map the Person ID's into a new stream which you can then apply Collectors.joining on.

String result = personList.stream().map(Person::getId)
                          .collect(Collectors.joining(","));

如果您的ID字段不是字符串而是一个 int 或其他一些原始数字类型,那么你应该使用下面的解决方案:

if your ID field is not a String but rather an int or some other primitive numeric type then you should use the solution below:

String result = personList.stream().map(p -> String.valueOf(p.getId()))
                          .collect(Collectors.joining(","));

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

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