0

I'm learning Stream and I tried to print an int Array using asList Method found in the class Arrays , unfortunatly i'm getting a wrong result.

could someone explain to me why i'm getting this wrong result.

public class array {

public static void main(String[] args) {
    /*my way*/
    int [] array = new int[]{1,2,3,7,1};
    Arrays.asList(array).stream().forEach(System.out::println);
    System.out.println();

    /*the good way*/
    Arrays.stream(array).forEach(System.out::print);

    }
    
}

result :

[I@3e3abc88

12371

Community
  • 1
  • 1
xmen-5
  • 1,806
  • 1
  • 23
  • 44

1 Answers1

3
Arrays.asList(array) -> a List<int[]>

Arrays.asList(array).stream() -> Stream<int[]>

Thus each element in the Stream in int[], not an int; so you are trying to print an array (Object); this will not work as you might expect.

In the second example:

Arrays.stream(array -> IntStream

thus this is working

Eugene
  • 117,005
  • 15
  • 201
  • 306
  • could you please write the correct awnser using aslist to print the element of the array because i tried to delete stream but i'm still getting the toString representation of the object. – xmen-5 Sep 11 '18 at 15:02
  • 2
    @zakzak `Arrays.asList(array).stream().forEach(anArray -> System.out.println(Arrays.toString(anArray)));` – Eugene Sep 11 '18 at 15:03
  • 1
    Or just `System.out.println(Arrays.toString(array));` – Holger Sep 12 '18 at 08:33