I know I can fill a normal vetor/list with some zeros
with the following statement:
double[][] list = new double[10][10]; // It will automatically inserts 0's in all positions.
List<Double> list1 = new ArrayList(new ArrayList(Collections.nCopies(10, 0d))); // Also
I want to make the same thing BUT using a 2D list, is it possible?
List<List<Double>> list2 = new ArrayList();
// It doesn't work -> List<List<Double>> list2 = new ArrayList(new ArrayList(Collections.nCopies(10, 0d)));
By the way, I want to avoid to use explicit loop.
List<Double> list1 = new ArrayList(new ArrayList(Collections.nCopies(10, 0d)));
This is redundant. You pass the list to a secound constructor. This is enough:
List<Double> list1 = new ArrayList(Collections.nCopies(10, 0d));
With a 2D List you can do it like this:
List<List<Double>> list2 = new ArrayList(Collections.nCopies(10, new ArrayList(Collections.nCopies(10, 0d))));
But be carefull, the list contains ten times the reference to the same list.
If you want to have different lists and avoid and explicit for loop, you can use an implicit for loop and java 8.
List<List<Double>> list2 = new ArrayList();
Collections.nCopies(10, new ArrayList(Collections.nCopies(10, 0d))).forEach((list) -> list2.add(new ArrayList(list)));
Stream, for example:
List<List<Double>> list2 = IntStream.range(0, 10)
.mapToObj(i -> new ArrayList<Double>(Collections.nCopies(10, 0d)))
.collect(Collectors.toList());
It will also iterate, but implicitly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With