Home > OS >  How to print individual elements of an "int[]" using a Stream in Java?
How to print individual elements of an "int[]" using a Stream in Java?

Time:08-27

    int[] a = {10, 20, 30, 40};
    Stream.of(a).forEach(System.out::println);
    

for this code, i'm expecting the output (the values): 10 20 30 40
But it is printing (the reference): [I@6d86b085

Am I missing anything (or) any changes in the Streams?

CodePudding user response:

There are multiple ways you could do this. For example, you could change Stream.of to IntStream.of like

IntStream.of(a).forEach(System.out::println);

Or, you could apply a flatMap to the Stream.of like

Stream.of(a).flatMap(x -> IntStream.of(x).boxed()).forEach(System.out::println);

Or, you could use Arrays.stream like

Arrays.stream(a).forEach(System.out::println);

I would recommend the first or the third, but I included the second to demonstrate that you can make it work with an int[] (just remember an int[] is an Object).

CodePudding user response:

Oh my bad, I have taken an int array instead of Integer array. The following code works fine.

Integer[] a = {10, 20, 30, 40};
Stream.of(a).forEach(System.out::println);
  • Related