Java8 how to create nested lists?
Learn and play with Java8. Trying to create a 2D array.
final List<Integer> row = IntStream.range(0, 3)
.boxed()
.collect(Collectors.toList());
List<List<Integer>> arr2D = IntStream.range(0, 3)
.map(i -> arr2D.add(i, row)); // will not compile
how to put string into 2D array? and is this the correct way to use Java8?
+3
source to share
2 answers
Your question mentions arrays, but your code only has lists. If you want to create a nested list:
List<List<Integer>> arr2D = IntStream.range(0, 3)
.mapToObj(i -> row)
.collect(Collectors.toList());
Of course, with this code, all internal lists will be identical (i.e. the same instance). If you want each inner list to be a different instance:
List<List<Integer>> arr2D = IntStream.range(0, 3)
.mapToObj(i -> new ArrayList<Integer>(row))
.collect(Collectors.toList());
+6
source to share