[英]Java: How convert a List of Object to List of String?
I have a class named Pessoa
我有一堂课叫Pessoa
Classe Pessoa {
Id Integer,
Nome String
}
And in another part I have a list of objects of this class: 在另一部分中,我列出了此类的对象:
List<Pessoa> pessoas = getPessoas();
The above code works properly, but I need to transform it into a List<String>
, where it only includes Nome
field of class Pessoa
. 上面的代码可以正常工作,但是我需要将其转换为List<String>
,其中它仅包含Pessoa
类的Nome
字段。
How can I do that? 我怎样才能做到这一点?
You can do it easily with Java 8 Streams : 您可以使用Java 8 Streams轻松实现:
List<String> names = pessoas.stream().map(Pessoa::getName).collect(Collectors.toList());
This is assuming your Pessoa
class has a getName()
method returning a String
. 这是假设您的Pessoa
类具有返回String
的getName()
方法。
Assuming that the attribute Nome is public and "pessoas" is your list of Pessoa: 假设属性Nome是public,而“ pessoas”是您的Pessoa列表:
public List<String> getNomes(List<Pessoa> pessoasList) {
List<String> nomes = new ArrayList<>();
for(Pessoa pessoaObj : pessoasList){
nomes.add(pessoaObj.nome)
}
return nomes;
} }
If you didn't understand that for loop, I suggest for you to search a little about that loop syntax. 如果您不了解for循环,建议您对该循环语法进行一些搜索。 It works very well for lists. 它非常适合列表。 Simple and easy. 简单容易。
Edit: As Eran said, it is easier using Streams, if using Java SDK 8 or newer : 编辑:正如Eran所说, 如果使用Java SDK 8或更高版本 ,使用Streams会更容易:
List<String> names = pessoas.stream().map(Pessoa::getName).collect(Collectors.toList());
Or, using Kotlin: 或者,使用Kotlin:
val names = pessoas.map{it.name}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.