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?

1
  • 1
    Could change the last line to: intPairs.stream().map(Arrays::toString).forEach(System.out::println); Commented Sep 14, 2017 at 3:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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<String> intPairs = numbers1.stream() .flatMap(i -> numbers2.stream() .filter(j -> (i+j)%3 == 0) .map(j -> Arrays.toString(new int[]{i,j}))) .collect(Collectors.toList());}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.