【发布时间】:2017-02-23 09:50:28
【问题描述】:
有一个带有属性 Developer 的列表 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,属性为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 以更优雅、更简洁的方式编写上述内容?
【问题讨论】:
-
这里真正的问题是为什么
Developer和ProductManager似乎没有从封装name和age的通用超类Person继承。在你升级到漂亮的 Java8 之前,你可能应该得到正确的设计。 -
@JimGarrison 是的,我同意你的观点,我需要更加关注基本面。如果属性比较多,可能超过20个,构造函数不能直接使用,如何转换?
-
如果
Developer和ProductManager有一个共同的基类Person,定义了所有共同的属性,那么在两个类中定义一个带有Person参数的构造函数就没有问题。这些构造函数只会委托给Person基类的构造函数来完成这项工作,因此它只需要实现一次。请注意,这是一种既定模式,即所有标准Collection类型都提供了一个构造函数,该构造函数接受Collection参数以进行复制。
标签: java list collections java-8 refactoring