Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to print a List of Arrays (with elements) using Java 8 Streams? [duplicate]

Tags:

java

java-8

public static void main(String[] args) {
    List<Integer> numbers1 = Arrays.asList(1,2,3);
    List<Integer> numbers2 = Arrays.asList(3,4);

    List<int[]> intPairs = numbers1.stream()
            .flatMap(i -> numbers2.stream()
                    .filter(j -> (i+j)%3 == 0)
                    .map(j -> new int[]{i,j}))
                    .collect(Collectors.toList());

    intPairs.stream().forEach(System.out::println);
}

For the above code, I am getting output as:

[I@214c265e
[I@448139f0

But my expectation is to get [(2, 4), (3, 3)].

Could you please guide me to achieve this?

like image 280
Saroj Avatar asked Sep 14 '25 10:09

Saroj


1 Answers

You can change the mapping part to List instead of using int[]:

....
.map(j -> Arrays.asList(i,j)))
....

And the output will be the following:

[2, 4]
[3, 3]

Here is the complete example:

public static void main(String[] args) {
    List<Integer> numbers1 = Arrays.asList(1,2,3);
    List<Integer> numbers2 = Arrays.asList(3,4);

    List<List<Integer>> intPairs = numbers1.stream()
            .flatMap(i -> numbers2.stream()
                    .filter(j -> (i+j)%3 == 0)
                    .map(j -> Arrays.asList(i,j)))
                    .collect(Collectors.toList());
    intPairs.stream().forEach(System.out::println);
}

Hope this helps.

like image 160
Arsen Davtyan Avatar answered Sep 17 '25 00:09

Arsen Davtyan