4
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?

Nissa
  • 4,636
  • 8
  • 29
  • 37
Saroj
  • 69
  • 3
  • 11
  • 1
    Could change the last line to: intPairs.stream().map(Arrays::toString).forEach(System.out::println); – jonD02 Sep 14 '17 at 03:29

1 Answers1

6

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.

Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
  • Thanks for you answer @arsen-davtyan, it serves my purpose well. But I was bit reluctant using List here. Instead I wanted the solution something like:- {List intPairs = numbers1.stream() .flatMap(i -> numbers2.stream() .filter(j -> (i+j)%3 == 0) .map(j -> Arrays.toString(new int[]{i,j}))) .collect(Collectors.toList());} – Saroj Sep 15 '17 at 13:33