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

本小妞迷上赌 提交于 2020-01-06 08:12:41

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/58776255/for-loop-to-add-custom-objects-to-arraylist-for-n-times-java8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!