[英]How to transform a List of Interface to List of class using Java Stream
I have a list of Interface -我有一个接口列表 -
List<NewHire> results;
I want to transform this to List of class (that implements NewHire)我想将其转换为类列表(实现 NewHire)
NewHireVO implements NewHire;
List<NewHire> result = //some data;
List<NewHireVO> newhires = new ArrayList<>();
for(NewHire n : result) {
newhires.add(new NewHireVO(n));
}
I would like to achieve the above using Stream.我想使用 Stream 实现上述目的。
List<NewHireVO> list = result.stream().map(x -> (NewHireVO) x).collect(Collectors.toList());
I assume the below, and populate with your input data.我假设如下,并填充您的输入数据。
public interface NewHire {
List<NewHire> getData();
}
public class NewHire0 implements NewHire{
@Override
public List<NewHire> getData() {
List<NewHire> list = new ArrayList<>();
list.add(new NewHire0());
return list;
}
}
public class NewHire0Main {
public static void main(String[] args) {
NewHire0 newHire0 = new NewHire0();
List<NewHire> data = newHire0.getData();
List<NewHire0> collect = data.stream()
.map(NewHire0.class::cast )
.collect(Collectors.toList());
}
}
Provided that NewHireVO
has a copy constructor, remapping can be done like this:如果NewHireVO
有一个复制构造函数,重映射可以这样完成:
List<NewHireVO> voList = result
.stream() // Stream<NewHire>
.map(NewHireVO::new) // Stream<NewHireVO>
.collect(Collectors.toList());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.