I have this array
int[][] currGrid = {{1,1},{1,2},{2,2}};
And this array is static so I want to create 2D arraylist using the same elements. Is there any way to create the arraylist for same in a single line without using add in Java?
It's unclear to me whether you meant you want to convert this given 2D array to a 2D list, or wether you meant to just create a new list with these values as a one-liner.
If you meant the former, you could stream the array and then stream each of its elements, and collect them:
List<List<Integer>> currGridList =
Arrays.stream(currGrid)
.map(g -> Arrays.stream(g).boxed().collect(Collectors.toList()))
.collect(Collectors.toList());
If you meant the latter, you could use List.of
:
List<List<Integer>> currGridList = List.of(List.of(1, 1), List.of(1, 2), List.of(2, 2));
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.