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


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

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());
}
Comments