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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40035102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:38:56  来源:igfitidea点击:

How to convert a list with properties to a another list the java 8 way?

javalistcollectionsjava-8refactoring

提问by Ivan

There is a List A with property Developer. Developer schema likes that:

有一个列表 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;
    }
}

List A with properties:

具有属性的列表 A:

List<Developer> A = ImmutableList.of(new Developer("Ivan", 25), new Developer("Curry", 28));

It is demanded to convert List A to List B which with property ProductManager and the properties is same as the ones of List A.

要求将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;
    }
}

In the old days, we would write codes like:

在过去,我们会编写如下代码:

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

How could we write the above in a more elegant and brief manner with Java 8?

我们如何用 Java 8 以更优雅和简短的方式编写上述内容?

采纳答案by Ramachandran.A.G

you will have to use something like below :

您将不得不使用以下内容:

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

// for large # of properties assuming the attributes have similar names //other wise with different names refer 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);

回答by Slava

Probably, like this:

大概是这样的:

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

回答by Saravana

If you are fine to add belwo constructor in ProductManger

如果您可以在 ProductManger 中添加 belwo 构造函数

public ProductManager(Developer d) {
    this.name = d.getName();
    this.age = d.getAge();
}

then to convert using constructor reference

然后使用构造函数引用进行转换

    List<Developer> developers = Arrays.asList(new Developer("abc", 25));
    List<ProductManager> managers = developers.stream().map(ProductManager::new).collect(Collectors.toList());
    System.out.println(managers);

otherwise you can provide custom mapper

否则你可以提供自定义映射器

Function<Developer, ProductManager> mapper = d -> new ProductManager(d.getName(), d.getAge()); 

use this in mapfunction

map函数中使用这个

Output

输出

[ProductManager [name=abc, age=25]]

回答by Mahesh

If there are more properties, maybe more than 20, and the constructor can not use directly, how to convert ?

如果属性比较多,可能超过20个,而且构造函数不能直接使用,怎么转换?

If you have any more than 3-4 properties to set, you should use a Builder, like so:

如果要设置的属性超过 3-4 个,则应使用 Builder,如下所示:

List<Developer> A = ImmutableList.of(new Developer("Ivan", 25),
                                     new Developer("Curry", 28));

Function<Developer, ProductManager> converter = dev -> new ProductManagerBuilder()
        .setAge(dev.getAge())
        .setName(dev.getName())
        .setProperty1(dev.getProperty1())
        .setProperty2(dev.getProperty2())
        ...
        .build();

List<ProductManager> productManagers = A.stream()
                                        .map(converter)
                                        .collect(toList());