Java 8有一个名为IntStream的新接口(interface)。我使用了它的of()静态方法,遇到了一个奇怪的错误:



但是正如您在以下代码中看到的那样,我确实使用了IntStream.of

import java.util.stream.IntStream;

public class Test {

    public static void main(String[] args) {
        int[] listOfNumbers = {5,4,13,7,7,8,9,10,5,92,11,3,4,2,1};
        System.out.println(IntStream.of(listOfNumbers).sum());
    }

}

而且,如果您检查API,您将看到该方法已经以与我所使用的相似的方式进行了声明。

最佳答案

尽管IntStream.of(int...)似乎有效,但您更有可能希望使用Arrays.stream(int[])

public void test() {
    int[] listOfNumbers = {5, 4, 13, 7, 7, 8, 9, 10, 5, 92, 11, 3, 4, 2, 1};
    // Works fine but is really designed for ints instead of int[]s.
    System.out.println(IntStream.of(listOfNumbers).sum());
    // Expected use.
    System.out.println(IntStream.of(5, 4, 13, 7, 7, 8, 9, 10, 5, 92, 11, 3, 4, 2, 1).sum());
    // Probably a better approach for an int[].
    System.out.println(Arrays.stream(listOfNumbers).sum());
}

10-07 21:03