供应商的Lambda表达式以生成IntStream [英] Lambda expression for supplier to generate IntStream

查看:169
本文介绍了供应商的Lambda表达式以生成IntStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用lambda表达式替换供应商代码

How do I replace the Supplier code here with lambda expression

IntStream inStream = Stream.generate(new Supplier<Integer>() {
    int x= 1;
    @Override
    public Integer get() {
        return x++ ;
    }
}).limit(10).mapToInt(t -> t.intValue());
inStream.forEach(System.out::println);

以上代码的输出为:

1
2
3
4
5
6
7
8
9
10


推荐答案

这样的东西如果你一定要使用 Stream.generate 具体来说:

Something like this if you're bound to use Stream.generate specifically :

IntStream inStream = Stream.generate(new AtomicInteger(1)::getAndIncrement)
        .limit(10)
        .mapToInt(t -> t);
inStream.forEach(System.out::println);

编辑 :使用 IntStream.generate ,您可以将其执行为

Edit: Using IntStream.generate, you can perform it as

IntStream.generate(new AtomicInteger(1)::getAndIncrement).limit(10);

注意 :更好的解决方案API设计肯定会使用 Stream.iterate

这篇关于供应商的Lambda表达式以生成IntStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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