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 asIntStream.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.
An IntStream interface extends the BaseStream interface in Java 8. It is a sequence of primitive int-value elements and a specialized stream for manipulating int values. We can also use the IntStream interface to iterate the elements of a collection in lambda expressions and method references.
range() method generates a stream of numbers starting from start value but stops before reaching the end value, i.e start value is inclusive and end value is exclusive. Example: IntStream. range(1,5) generates a stream of ' 1,2,3,4 ' of type int .
IntStream rangeClosed() method in Java The rangeClosed() class in the IntStream class returns a sequential ordered IntStream from startInclusive to endInclusive by an incremental step of 1. This includes both the startInclusive and endInclusive values.
IntStream of(int… values) returns a sequential ordered stream whose elements are the specified values. Parameters : IntStream : A sequence of primitive int-valued elements.
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>
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With