For循环将自定义对象添加到arraylist的次数为n-Java8 [英] For loop to add custom objects to arraylist for n times - Java8

查看:69
本文介绍了For循环将自定义对象添加到arraylist的次数为n-Java8的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一种老式的for循环,可将自定义对象添加到ArrayList.

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;
}

有没有办法通过使用java8来做到这一点?

Is there any way to do this by using java8?

我尝试使用Stream.generate(MyClass::new).limit(10);,但是在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.

有什么建议吗?

推荐答案

由于没有派生的通用类型并且不需要替代元素,因此,一种方法是简单地创建两种类型元素的nCopies并将它们添加到结果列表:

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;

使用Stream您可以将它们生成为

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

但是,从两个流中交替插入元素可能是绝对有效的要求,您可以使用此建议的解决方案答案,但其类型定义为当前对象的上级,或者修改实现以返回Object类型Stream. (老实说,尽管可以选择,我还是更喜欢前者.)

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

这篇关于For循环将自定义对象添加到arraylist的次数为n-Java8的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆