Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return 2-dimensional array in Java 8?

Tags:

java

java-8

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?

like image 921
Roman Shmandrovskyi Avatar asked Jan 28 '26 06:01

Roman Shmandrovskyi


1 Answers

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);
like image 69
Ousmane D. Avatar answered Jan 29 '26 20:01

Ousmane D.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!