Ivan Ivan - 1 year ago 69
Java Question

How to generate a ArrayList the Java 8 way?

In many integration/unit tests, we need to generate a list which uses a variable number of elements. In the old days, we would write code like:

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

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

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