Pamuleti Pullagura
Pamuleti Pullagura

Reputation: 61

For loop to add custom objects to arraylist for n times - Java8

We have an old-style for loop to add custom objects to ArrayList.

public List<Object> generateList() {
    List<Object> list = new ArrayList<Object>();

    for (int i = 0; i < 10; i++) {
        list.add(new Manager(50000, 10, "Finance Manager"));
        list.add(new Employee(30000, 5, "Accounts"));
    }
    return list;
}

Is there any way to do this by using java8?

I tried to use Stream.generate(MyClass::new).limit(10); but, I am not getting the right way in java8 to achieve the above functionality.

Any suggestions, please?

Upvotes: 1

Views: 1187

Answers (1)

Naman
Naman

Reputation: 31988

Since there is no common type derived and alternate elements are not required, one way is to simply create nCopies of both types of elements and add them to the resultant list:

List<Object> list = new ArrayList<>();
list.addAll(Collections.nCopies(10, new Manager(50000, 10, "Finance Manager")));
list.addAll(Collections.nCopies(10, new Employee(30000, 5, "Accounts")));
return list;

using Stream you can generate them as

Stream<Manager> managerStream = Stream.generate(() -> new Manager(...)).limit(10);
Stream<Employee> employeeStream = Stream.generate(() -> new Employee(...)).limit(10);
return Stream.concat(managerStream, employeeStream).collect(Collectors.toList());

But what could be an absolute valid requirement, to interleave elements from both stream alternatively, you can make use of the solution suggested in this answer, but with a type defined super to your current objects or modifying the implementation to return Object type Stream. (Honestly, I would prefer the former though given the choice.)

Upvotes: 3

Related Questions