有一份 list A 与房地产开发商。开发人员模式喜欢这样:
@Getter
@Setter
public class Developer {
private String name;
private int age;
public Developer(String name, int age) {
this.name = name;
this.age = age;
}
public Developer name(String name) {
this.name = name;
return this;
}
public Developer name(int age) {
this.age = age;
return this;
}
}
列表 A 的属性:
List<Developer> A = ImmutableList.of(new Developer("Ivan", 25), new Developer("Curry", 28));
要求将List A转换为List B,List B具有ProductManager属性,属性与List A相同。
@Getter
@Setter
public class ProductManager {
private String name;
private int age;
public ProductManager(String name, int age) {
this.name = name;
this.age = age;
}
public ProductManager name(String name) {
this.name = name;
return this;
}
public ProductManager name(int age) {
this.age = age;
return this;
}
}
在过去,我们会写这样的代码:
public List<ProductManager> convert() {
List<ProductManager> pros = new ArrayList<>();
for (Developer dev: A) {
ProductManager manager = new ProductManager();
manager.setName(dev.getName());
manager.setAge(dev.getAge());
pros.add(manager);
}
return pros;
}
我们如何使用 Java 8 以更优雅和简洁的方式编写上述内容?
最佳答案
你将不得不使用类似下面的东西:
List<ProductManager> B = A.stream()
.map(developer -> new ProductManager(developer.getName(), developer.getAge()))
.collect(Collectors.toList());
//假设属性具有相似名称的大量属性 //否则用不同的名字引用this
List<ProductManager> B = A.stream().map(developer -> {
ProductManager productManager = new ProductManager();
try {
PropertyUtils.copyProperties(productManager, developer);
} catch (Exception ex) {
ex.printStackTrace();
}
return productManager;
}).collect(Collectors.toList());
B.forEach(System.out::println);
关于java - 如何以 Java 8 方式将具有属性的列表转换为另一个列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40035102/