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?

Roman Shmandrovskyi
  • 883
  • 2
  • 8
  • 22
  • 2
    `IntStream.rangeClosed(0, 4).map(i -> new Object[]{users.get(i), datas.get(i)}).toArray(Object[][]::new)` – Boris the Spider Feb 10 '18 at 16:23
  • Also see https://stackoverflow.com/questions/17640754/zipping-streams-using-jdk8-with-lambda-java-util-stream-streams-zip#23529010 – Devstr Feb 10 '18 at 16:24
  • If you can use Guava, there's [`Streams.zip`](https://google.github.io/guava/releases/snapshot/api/docs/com/google/common/collect/Streams.html#zip-java.util.stream.Stream-java.util.stream.Stream-java.util.function.BiFunction-) function. – Devstr Feb 10 '18 at 16:24
  • Poor question title. You should mention streams in the title. – Robert Feb 10 '18 at 17:47

1 Answers1

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);
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126