Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Streams int and Integer

Was just getting my hands dirty with Java 8 and stumbled on a behaviour as below -

public static void main(String... args){
    System.out.println("[Start]");
    int[] ints = {1, 2, 3, 4};
    Stream.of(ints).forEach(i->System.out.println("Int : "+i));


    Integer[] integerNums = {1, 2, 3, 4};
    Stream.of(integerNums).forEach(i->System.out.println("Integer : "+i));

    System.out.println("[End]");
}

And the output is :

[Start]
Int : [I@5acf9800
Integer : 1
Integer : 2
Integer : 3
Integer : 4
[End]

Whereas I was expecting the code to print all int's and Integer's in both the cases? Any insights on this would be greatly helpful...

like image 315
g0c00l.g33k Avatar asked Feb 22 '14 04:02

g0c00l.g33k


People also ask

What are two types of streams in Java 8?

With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.

Does Java 8 support streams?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.

What is an Integer stream in Java?

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.


1 Answers

Generics don't work with primitive types. The Stream.of method is declared as

static <T> Stream<T> of(T... values)

When you use

Stream.of(ints)

where ints is an int[], Java doesn't see a number of int elements (primitive types), it sees a single int[] element (which is a reference type). So the single int[] is bound as the only element in the array represented by T... values.

So values becomes an int[][] and each of its elements is an int[], which print like

[I@5acf9800
like image 93
Sotirios Delimanolis Avatar answered Oct 07 '22 04:10

Sotirios Delimanolis