编写增量整数供应商

时间:2015-01-12 11:13:06

标签: java functional-programming

我正在努力掌握Java 8函数式编程。我尝试在功能上写下以下IntSupplier,但我一直在遇到问题。

import java.util.function.IntSupplier;

    @Test public void test_nonFunctional() {
        IntSupplier supplier = new IntSupplier() {
            private int nextInt = 0;
            @Override public int getAsInt() {
                return nextInt++;
            }
        };
    }

这是我的尝试。这些问题在代码中标记为注释。

import org.junit.Test;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntSupplier;

public class IntSupplierTest {
    @Test public void test_nonFunctional() {
        IntSupplier supplier = new IntSupplier() {
            private int nextInt = 0;
            @Override public int getAsInt() { return nextInt++; }
        }; // Works but is not functional.
    }

    @Test public void test_naive() {
        int nextInt = 0;
        IntSupplier supplier = () -> nextInt++; // Doesn't compile: requires nextInt to be final.
    }

    @Test public void test_nextIntIsFinal() {
        final int nextInt = 0;
        IntSupplier supplier = () -> nextInt++; // Doesn't compile: nextInt can't be incremented because it's final.
    }

    @Test public void test_useWrapper() {
        final AtomicInteger nextInt = new AtomicInteger(0);
        IntSupplier supplier = () -> nextInt.getAndIncrement(); // It is not the same as my original question as this test uses an extra object.
    }
}

如果答案只是在没有使用额外物品的情况下无法完成,请说明一下。

3 个答案:

答案 0 :(得分:3)

您对问题的定义已​​无法正常运行。在功能上,没有参数就不能有不同的输出。这就是定义。但是如何创建一个可以在java库中看到的数字序列:java.util.function.IntUnaryOperator。它的使用方式如下:

IntStream.iterate(0, i -> i+1).limit(10).foreach(System.out::printLn);

答案 1 :(得分:0)

有一种解决此问题的标准方法:

int[] nextInt = { 0 }; // optionally mark as final
IntSupplier supplier = () -> nextInt[0]++;

但它实际上并没有比“工作但没有功能”解决方案具有更多功能。

答案 2 :(得分:0)

您可以执行以下操作:

IntSupplier supplier = new AtomicInteger(0)::incrementAndGet;
相关问题