Ivan Ivan - 1 year ago 105
Java Question

How to generate a ArrayList in Java 8

Most of the integration/unit tests, we need to generate a list which uses random elements, in the old days, we write codes like that:

public static List<String> getStringList(int i)
List<String> list = new ArrayList<String>();
for (int j = 0; j < i; j++)
return list;

How to write the above codes in java 8, which could be more elegant and brief.


Answer Source

You could use an IntStream range, map it to String and collect it to a List like

public static List<String> getStringList(int i) {
    return IntStream.range(0, i).mapToObj(String::valueOf)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download