简体   繁体   English

使用Lambda创建带有空对象的ArrayList

[英]Create an ArrayList with empty objects using lambda

I want to create an ArrayList of objects that have an id and an empty list using streams. 我想使用流创建具有id和空列表的对象的ArrayList。 I tried different ways but none seams to work. 我尝试了不同的方法,但是没有接缝。 If someone can give me some hits will help me a lot. 如果有人可以给我一些帮助,对我有很大帮助。 Here is the code that I want to convert to Java 8: 这是我想转换为Java 8的代码:

    this.registers = new ArrayList<Supplier>();
    for (int i = 0; i < this.numberOfSuppliers; i++) {
        Supplier supplier = new Supplier();
        supplier.setSupplierNumber(i);
        supplier.setMaterials(new ArrayList<Warehouse>());
        this.registers.add(supplier);
    }

Thank you in advance. 先感谢您。

You might consider adding a constructor to Supplier that takes the id as a parameter, and initializes the list of materials, so you don't have to expose a setter. 您可以考虑将一个构造函数添加到Supplier中,该构造函数将id作为参数,并初始化物料清单,因此不必公开setter。 Then the solution using either the loop or streams becomes much simpler. 然后,使用循环或流的解决方案变得更加简单。

public void buildSuppliersWithLoop()
{
    ArrayList<Supplier> registers = new ArrayList<>()
    int numberOfSuppliers = 100;
    for (int i = 0; i < numberOfSuppliers; i++)
    {
        registers.add(new Supplier(i));
    }
}

public void buildSuppliersWithStream()
{
    int numberOfSuppliers = 100;
    List<Supplier> registers = IntStream.range(0, numberOfSuppliers)
            .mapToObj(Supplier::new)
            .collect(Collectors.toList());
}

public class Supplier
{
    private int number;
    private List<Warehouse> materials;

    public Supplier(int number)
    {
        this.number = number;
        this.materials = new ArrayList<>();
    }
}

public class Warehouse
{
}

It is not my preferred approach (I think the for loop is fine here), but in streams you can do this: 这不是我的首选方法(我认为for循环在这里很好),但是在流中可以执行以下操作:

this.registers = IntStream.range(0, this.numberOfSuppliers)
         .map(i -> {
                       Supplier supplier = new Supplier();
                       supplier.setSupplierNumber(i);
                       supplier.setMaterials(new ArrayList<Warehouse>());
                       return supplier;
         })
         .collect(Collectors.toList());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM