How to create a list of objects using a range of numbers in Java 8

The Java 8 Stream API could come in handy when you would like to generate a series of objects for example for using them in a unit test.

The following snippet generates a list of 5 User objects with the id and name populated:

List<User> users = IntStream.range(0, 5).mapToObj(i -> {

    User user = new User();
    user.setName(USER_NAME_PREFIX + String.valueOf(i));

    return user;


If you have a suitable constructor, you can even make it a lot shorter:

List<User> users = IntStream.range(0, 5)
    .mapToObj(i -> new User(i, USER_NAME_PREFIX + String.valueOf(i)))