Java 8有一个名为IntStream
的新界面。我使用了它的of()
静态方法并遇到了一个奇怪的错误:
接口
进行访问IntStream
的这种静态方法只能作为IntStream.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,您将看到该方法已按照我使用的方式声明。
答案 0 :(得分:5)
您需要将项目设置为使用Java 8.例如,如果您使用的是maven,请将以下代码段放在您的pom中:
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
答案 1 :(得分:3)
虽然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());
}