[英]Java 8 create map a list of a complex type to list of one of its fields
I have a list from some complex type and I want to figure a neat way to construct a list only from one of its fields using Java 8's streams. 我有一些复杂类型的列表,我想想出一种巧妙的方法,可以使用Java 8的流仅从其字段之一构造列表。 Let's take as an example:
让我们举个例子:
public static class Test {
public Test(String name) {
this.name = name;
}
public String getName() {
return name;
}
private String name;
// other fields
}
And imagine that I have a List<Test> l;
想象一下我有一个
List<Test> l;
. 。 Now I want to create a new list that contains the values of
name
of all elements in l
. 现在,我想创建一个新列表,其中包含
l
中所有元素的name
值。 One possible solution that I found is the following: 我发现的一种可能的解决方案如下:
List<String> names = l.stream().map(u ->u.getName()).
collect(Collectors.<String> toList());
But I was wondering if there is a better way to do this - map a list of a given type to another list of different type. 但是我想知道是否有更好的方法可以将给定类型的列表映射到另一个不同类型的列表。
Using method references is shorter : 使用方法引用更短:
List<String> names = l.stream().map(Test::getName).
collect(Collectors.toList());
You can't avoid at least two Stream
methods, since you must first convert each Test
instance to a String
instance (using map()
) and then you must run some terminal operation on the Stream
in order to process the Stream
pipeline (in your case you chose to collect the Stream
of String
s into a List
). 您不能避免至少两个
Stream
方法,因为您必须首先将每个Test
实例转换为String
实例(使用map()
),然后必须在Stream
上运行一些终端操作才能处理Stream
管道(在您的如果您选择将String
的Stream
收集到List
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.