Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Collecting value of int array using normal JAVA Stream

In my program, I am trying to print sorted int array using stream. But I am getting false output while using normal stream. And correct details are getting printed while using int stream.

Please refer below core snippet for more details.

package com.test.sort.bubblesort;

import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class BubbleSortWithRecursion {

    public static void bubbleSort(int[] arr, int n) {

        if (n < 2) {
            return;
        }

        int prevValue;
        int nextValue;
        for (int index = 0; index < n-1; index++) {
            prevValue = arr[index];
            nextValue = arr[index+1];

            if  (prevValue > nextValue) {
                arr[index] = nextValue;
                arr[index+1] = prevValue;
            }
        }

        bubbleSort(arr, n-1);
    }

    public static void main(String[] args) {
        int arr[] = new int[] {10,1,56,8,78,0,12};
        bubbleSort(arr, arr.length);

        **//False Output** :  [I@776ec8df
        String output = Arrays.asList(arr)
            .stream()
            .map(x -> String.valueOf(x))
            .collect(Collectors.joining(","));

        System.out.println(output);

        //Correct Output : 0,1,8,10,12,56,78
        String output2 = IntStream
            .of(arr)
            .boxed()
            .map(x -> Integer.toString(x))
            .collect(Collectors.joining(","));

        System.out.println(output2);

    }


}

And I am getting following output on console :

[I@776ec8df
0,1,8,10,12,56,78

The fist line of output was generated using normal java stream which is not correct.

Why am I getting false content using normal JAVA stream ? Am I missing something here ?

like image 975
Gunjan Shah Avatar asked Mar 24 '19 07:03

Gunjan Shah


People also ask

Can I Stream an array in Java?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.

What is Stream () method in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.

Which method in Stream can be used to create an array from the Stream?

toArray() The toArray() method is a built-in method from the Stream class which is really convenient to use when converting from a Stream to an array.


Video Answer


2 Answers

You can solve your issue like so :

String output = Arrays.stream(arr)
        .boxed()
        .map(String::valueOf)
        .collect(Collectors.joining(",")); // 0,1,8,10,12,56,78

Explain what happen :

when you use Arrays.asList() which look :

public static <T> List<T> asList(T... a) {
    return new ArrayList<>(a);
}

it took varargs of type T, in your case you use it for int[] Object, so Arrays.asList() will return List of int[] and not a stream of ints, so instead you have to use Arrays.stream which look like this :

public static IntStream stream(int[] array) {
    return stream(array, 0, array.length);
}

to get the correct data.

like image 89
YCF_L Avatar answered Oct 28 '22 15:10

YCF_L


Arrays.asList(arr) returns a List<int[]> whose only element is arr. Therefore streaming that List and then mapping that single element to String.valueOf(x) and collecting with Collectors.joining(",") will result in a String whose value is that single array's toString(), which is the output you see.

String output = Arrays.asList(arr) // List<int[]>
    .stream() // Stream<int[]>
    .map(x -> String.valueOf(x)) // Stream<String> having a single element - "[I@776ec8df"
    .collect(Collectors.joining(",")); // "[I@776ec8df"

When you create an IntStream from the int array, you get a stream of the individual elements (the int values), so you can box them, convert then to Strings and join them to get the desired output.

You can make your first snippet work if you change:

int arr[] = new int[] {10,1,56,8,78,0,12};

to:

Integer arr[] = new Integer[] {10,1,56,8,78,0,12};

since this way Arrays.asList(arr) will produce a List<Integer> containing all the elements of the input array.

like image 40
Eran Avatar answered Oct 28 '22 16:10

Eran