1

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?

Naman
  • 27,789
  • 26
  • 218
  • 353
  • Why would you use `List` and does it matter to have the Manager and Employee object in every alternate position or you just want to have 10 Employee and 10 Manager items in the list? – Naman Nov 09 '19 at 03:58
  • The alternative position is not mandatory.Just I need to have 10 employee and 10 manager objects in my list. – Pamuleti Pullagura Nov 09 '19 at 04:08

1 Answers1

3

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.)

Naman
  • 27,789
  • 26
  • 218
  • 353
  • 4
    Keep in mind that `Collections.nCopies` returns a list that will contain the same object *n* times whereas `Stream.generate(() -> new ...(...)).limit(...)` will create *n* distinct objects. – Holger Nov 11 '19 at 07:19