重用集创建(Java)

时间:2017-09-26 11:47:42

标签: java csv

我目前正在开展一项任务,我正在努力为我创建的单个集合创建多个值:

package lacsp.portal.backing.oracle.webcenter.portalapp.pages;

import java.io.FileWriter;

import java.math.BigDecimal;

import java.text.DecimalFormat;
import java.text.NumberFormat;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;

public class CSVUtilsExample {

public static void main(String[] args) throws Exception {

    Random rand = new Random();
    int randomSets = rand.nextInt(100000) + 1;
    int val = 1;
    final DecimalFormat decimalFormat = new DecimalFormat("0000");
    String csvFile = "C:/work/tableOutput.csv";
    FileWriter writer = new FileWriter(csvFile);
    CSVUtils.writeLine(writer, Arrays.asList("SET_ID", "INT_VALUE"));
    // Will loop whilst val is less than the random sets generated 
    while (val <= randomSets) {
        int random = rand.nextInt(100000) + 1;
        List<Orders> orders =
            Arrays.asList(new Orders("S" + decimalFormat.format(val),
                                     new Integer(random)));
        for (Orders o : orders) {
            List<String> list = new ArrayList<String>();
            list.add(o.getSET_ID());
            list.add(o.getINT_VALUE().toString());
            CSVUtils.writeLine(writer, list);

            //try custom separator and quote.
            //CSVUtils.writeLine(writer, list, '|', '\"');

        }
        val++;
    }
    writer.flush();
    writer.close();

}


}

上面的代码将写出.csv文件并将随机的INT_VALUE分配给创建的SET_ID。目前每个SET_ID只有1个INT_VALUE但是我的问题是如何才能使它成为一个随机数将INT_VALUES分配给单个SET_ID?

E.G

#SET_ID ## INT_VALUE#

S0001

    55
    712
    379
    1
    1111

S0002

    76  
    985

S0003

    1
    1059
    23
    22
    77

............

Orders.Java

package lacsp.portal.backing.oracle.webcenter.portalapp.pages;

public class Orders {

private String SET_ID;
private Integer INT_VALUE;

public Orders(String SET_ID, Integer INT_VALUE) {
    this.SET_ID = SET_ID;
    this.INT_VALUE = INT_VALUE;

}

public void setSET_ID(String SET_ID) {
    this.SET_ID = SET_ID;
}

public String getSET_ID() {
    return SET_ID;
}

public void setINT_VALUE(Integer INT_VALUE) {
    this.INT_VALUE = INT_VALUE;
}

public Integer getINT_VALUE() {
    return INT_VALUE;
}
}

1 个答案:

答案 0 :(得分:0)

在这一行:

List<Orders> orders =
        Arrays.asList(new Orders("S" + decimalFormat.format(val),
                                 new Integer(random)));

您创建的列表只包含1个项目。我想你想要创建一个随机数量的项目,每个项目都有随机ID:

// Create an empty list
List<Orders> orders = new ArrayList<>();
// Single set id for all items
String setId = "S" + decimalFormat.format(val);
// Create a bunch of orders
int numOrders = rand.nextInt(100);
for (int i = 0; i < numOrders; i++) {
    // Create a new Order and add it to the list
    orders.add(new Orders(setId, rand.nextInt(10000) + 1));
}

另外,您将课程命名为Orders,但它确实应该是Order,因为它只是一个订单。