Java8中的“map-based memoized”? [英] `map-based memoized` in Java8?

查看:165
本文介绍了Java8中的“map-based memoized”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我之前的问题

在Java 8中记录的无限斐波纳契序列

我问如何编写一个代码来定义无限序列的斐波纳契简洁的数学方式与Java8 Stream的记忆。

I asked how to write a code to define the infinite sequence of fibonacci in concise math manner with memoization with Java8 Stream.

幸运的是,我有一个答案,下面的代码似乎很好:

Thankfully, I've got an answer, and the code below seems to work well:

    LongStream fibs = Stream
            .iterate(
            new long[]{1, 1},
            f -> new long[]{f[1], f[0] + f[1]}
            )
            .mapToLong(f -> f[0]);

    fibs
            .limit(30)
            .forEach(System.out::println);

1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765
10946
17711
28657
46368
75025
121393
196418
317811
514229
832040

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 10946 17711 28657 46368 75025 121393 196418 317811 514229 832040

尽管Java8中函数的代码风格呈现仍然混淆我,我可以相当肯定它对应于斐波纳契序列的数学定义。

Although the code style presentation of the function in Java8 still confuses me, I could fairly confirm it corresponds the math definition of fibonacci sequence.

计算速度表明它记录了这个功能,他说

The computing speed suggests it memoizes the function, and he says


你可以把你的地图记录的斐波那契(x)和一个无限的流,像这样:

You can take your map-based memoized fibonacci(x) and make an infinite stream out of it like this:

什么是code> Java8中的基于map的已记录的

What is the map-based memoized in Java8?

另外,我无法遵循

.mapToLong(f - > f [0]);

你解释任何参考/文档也不胜感激。谢谢。

Can you explain. Any reference/documentation is also appreciated. Thanks.

推荐答案

正如Misha所说,这是供应商< Long> 被记住的功能界面,因为它存储两个私有变量 n1 n2 。然后,该对象具有 可变 状态,并具有副作用。使用paralellization可能会导致问题。

As Misha said, it's the Supplier<Long> functional interface that's memoised because it stores two private variables n1 and n2. The object has then a mutable state and has side effects. It could cause problems when using paralellization.

new Supplier<Long>() {
    private long n1 = 1;
    private long n2 = 2;

    @Override
    public Long get() {
        long fibonacci = n1;
        long n3 = n2 + n1;
        n1 = n2;
        n2 = n3;
        return fibonacci;
    }
}

iterate 是不可变的,可以进行并行化。它从[1,1]开始生成一个大小为2的 long 数组,并迭代地应用函数 f - > new long [] {f [1],f [0] + f [1]}

At opposite the solution with the iterate is immutable and is ready for parallelization. It generates a stream of long arrays of size 2, starting from [1,1] and iteratively applying the function f -> new long[]{f[1], f[0] + f[1]}

.iterate(
        new long[]{1, 1},
        f -> new long[]{f[1], f[0] + f[1]}
        )

这篇关于Java8中的“map-based memoized”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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