Convert Nested List of Integers to a two dimensional array using Streams ( List<List<Integer>> -> int[][] ) [duplicate]

倖福魔咒の 提交于 2021-01-29 07:58:07

问题


I searched for similar questions but I found only for the object String which dont apply to this case:

Want to convert List<List<Integer>> list to int[][] array using streams

So far I got this:

int[][] array= list.stream().map(List::toArray)...

I used as a base other similar questions I found. But these use String and can't make it work for Integers->int:

// Example with String 1:    
String[][] array = list.stream()
        .map(l -> l.stream().toArray(String[]::new))
        .toArray(String[][]::new);

// Example with String 2:    
    final List<List<String>> list = ...;
    final String[][] array = list.stream().map(List::toArray).toArray(String[][]::new);

回答1:


You only need to make a few modifications to the String[][] solution:

List<List<Integer>> lists = ...;
int[][] arrays = lists.stream()                                // Stream<List<Integer>>
        .map(list -> list.stream().mapToInt(i -> i).toArray()) // Stream<int[]>
        .toArray(int[][]::new);

The mapToInt(i -> i) is unboxing each Integer (i.e. Integerint).

See:

  • Stream#mapToInt(ToIntFunction)
  • IntStream#toArray()


来源:https://stackoverflow.com/questions/58228825/convert-nested-list-of-integers-to-a-two-dimensional-array-using-streams-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!