9

Java 8 has a new interface, named IntStream. I used its of() static method and encountered a strange error:

This static method of interface IntStream can only be accessed as IntStream.of

But as you can see in the following code, I, exactly, used 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());
    }

}

Moreover, if you check the API, you will see that the method has been declared in the similar way which I used.

4
  • I don't understand the problem. It said it could be used as IntStream.of and you used it as IntStream.of
    – aioobe
    Commented Aug 18, 2014 at 9:36
  • Yes; that's a strange compile error which seems to make no sense... But anyway my code doesn't work, now.
    – hossayni
    Commented Aug 18, 2014 at 10:23
  • 1
    What IDE are you using? Works fine in Netbeans - prints 181. Commented Aug 18, 2014 at 10:31
  • I saw this same error in Eclipse with Java 8 after accessing the same static method the same way. After restarting Eclipse a few times, the error went away.
    – rmtheis
    Commented May 16, 2015 at 23:27

2 Answers 2

6

You need to set the project to use Java 8. For example if you are using maven, place the following snippet in your 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
  • Thanks, using Maven inside my project, I did not notice that the configuration was bad.
    – loloof64
    Commented Apr 9, 2015 at 15:48
3

Although IntStream.of(int...) seems to work it is more likely that you are expected to use 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());
}
1
  • Thanks; that was completely useful; but I don't know why the first code doesn't work in my Eclipse while I have added the java 8 to it;
    – hossayni
    Commented Aug 18, 2014 at 13:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.