3

I have a method that returns a matrix, where row is a pair of User and MessageData.

public static Object[][] getData() {
    DomXmlParsing parse = new DomXmlParsing();
    List<User> users = parse.getUsers();
    List<MessageData> datas = parse.getDataForMessage();
    return new Object[][]{
            {users.get(0), datas.get(0)},
            {users.get(1), datas.get(1)},
            {users.get(2), datas.get(2)},
            {users.get(3), datas.get(3)},
            {users.get(4), datas.get(4)}
    };
}

How can I return this matrix using Stream API of Java 8?

4
  • 2
    IntStream.rangeClosed(0, 4).map(i -> new Object[]{users.get(i), datas.get(i)}).toArray(Object[][]::new) Commented Feb 10, 2018 at 16:23
  • Also see stackoverflow.com/questions/17640754/… Commented Feb 10, 2018 at 16:24
  • If you can use Guava, there's Streams.zip function. Commented Feb 10, 2018 at 16:24
  • Poor question title. You should mention streams in the title. Commented Feb 10, 2018 at 17:47

1 Answer 1

6

You can accomplish the task at hand with:

return IntStream.range(0, users.size())
                .mapToObj(i -> new Object[]{users.get(i), datas.get(i)})
                .toArray(Object[][]::new);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.