简体   繁体   English

如何在 Java 中使用流/lambda 重复调用 0 参数函数并将返回值收集到列表中?

[英]How to call a 0-argument function repeatedly and collect the return values into a list using stream/lambda in Java?

Say I would like to create a "random" list of 100 users by using the fakeRandomUser function below.假设我想使用下面的fakeRandomUser函数创建一个包含 100 个用户的“随机”列表。

public class User {
    String name;

    static public User fakeRandomUser() {
        User user = new User();
        user.name = "foobar";
        return user;
    }

}

Is it possible to do this with the Stream API instead of appending to a list in a loop?是否可以使用 Stream API 执行此操作而不是附加到循环中的列表?

One way is to construct an IntStream of 100 items, and map it to your fakeRandomUser function:一种方法是构造一个IntStream 100 个项目的IntStream ,并将其映射到您的fakeRandomUser函数:

List<User> users = IntStream.range(0, 100)
    .mapToObj(e -> User.fakeRandomUser())
    .collect(Collectors.toList());

Another way is to use Stream.generate() , like so:另一种方法是使用Stream.generate() ,如下所示:

List<User> users = Stream.generate(User::fakeRandomUser)
    .limit(100)
    .collect(Collectors.toList())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM