如何以 Java 8 方式将具有属性的列表转换为另一个列表?

新手上路,请多包涵

有一个列表 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 以更优雅和简洁的方式编写上述内容?

原文由 Ivan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 504
2 个回答

你将不得不使用类似下面的东西:

 List<ProductManager> B = A.stream()
        .map(developer -> new ProductManager(developer.getName(), developer.getAge()))
        .collect(Collectors.toList());

// 对于大量的属性,假设属性具有相似的名称 // 否则使用不同的名称请参考

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);

原文由 Ramachandran.A.G 发布,翻译遵循 CC BY-SA 3.0 许可协议

大概是这样的:

 List<ProductManager> B = A.stream()
        .map(developer -> new ProductManager(developer.name, developer.age))
        .collect(Collectors.toList());

原文由 Slava 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题