简体   繁体   中英

How can I return 2-dimensional array in 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM