Ivan Ivan - 2 months ago 6
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++)
{
list.add(String.valueOf(j));
}
return list;
}


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

thanks.

Answer

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)
            .collect(Collectors.toList());
}