Jose Ng
Jose Ng

Reputation: 9

Make a Stream of arrays of elements from one array of these elements is not possible in Java

Given the fragment code:

    Integer [] arrayIntegers_1 = {100,5,80,9,65,200};
    Integer [] arrayIntegers_2 = {30,99,800};
    Integer [] arrayIntegers_3 = {166,520,7};

    Stream<Integer[]> streamOfArraysOfIntegers=Stream.of(arrayIntegers_1,arrayIntegers_2,arrayIntegers_3);
    //OK, it is a Stream of arrays of Integers

    Stream<Integer[]> streamOfArraysOfIntegers_1=Stream.of(arrayIntegers_1);
    //Compilation fail in this line, Java cannot make a Stream of arrays of Integers or others objects from one (1) array

    Stream<Integer> streamOfOfIntegers=Stream.of(arrayIntegers_1);
    //From one (1) array Java makes a Stream of elements in this array, in this case it is a Stream of Integers 

In the line with fail compilation, I waited Java makes a Stream of arrays of Integers with one array of Integers, but not. In the next line, We can see Java makes a Stream of Integers from one array.

However, with the Collections doesn´t happen that, how we can see in the next fragment code, last line,

    ArrayList<Integer> listOfIntegers=new ArrayList<>();
    listOfIntegers.add(300); listOfIntegers.add(5); listOfIntegers.add(98); listOfIntegers.add(1); listOfIntegers.add(7);
    ArrayList<Integer> listOfIntegers_1=new ArrayList<>();
    listOfIntegers_1.add(999); listOfIntegers_1.add(3); listOfIntegers_1.add(85);   listOfIntegers_1.add(561); listOfIntegers_1.add(42);

    Stream<ArrayList<Integer>> streamOfListofIntegers=Stream.of(listOfIntegers,listOfIntegers_1);
    Stream<ArrayList<Integer>> streamOfListofIntegers_1=Stream.of(listOfIntegers); //Stream of ArrayList of Integers with one (1) ArrayList of Integers

I`d thank any comment.

Upvotes: 0

Views: 65

Answers (1)

ernest_k
ernest_k

Reputation: 45329

If you want to force Stream.of to build a Stream<Integer[]>, you can use:

Stream<Integer[]> streamOfArraysOfIntegers_1 = 
                     Stream.<Integer[]>of(arrayIntegers_1);

The reason is that Stream.of takes a var-arg, which means it makes a stream of individual elements of that array when given a single array.

You wouldn't need to do that if you actually pass it multiple arrays:

Stream<Integer[]> streamOfArraysOfIntegers_1 = 
                     Stream.of(arrayIntegers_1, arrayIntegers_2);

The comparison of this behavior to that of collections is not relevant. This affects arrays because they have a relationship with var-args (You can pass T[] as argument to a method that has T... as parameter); and that is not the case for collections.

Upvotes: 5

Related Questions