Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fill a 2D ArrayList with zeros

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.

like image 210
developer033 Avatar asked Mar 31 '16 13:03

developer033


2 Answers

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)));
like image 152
kai Avatar answered Oct 03 '22 07:10

kai


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.

like image 38
Alex Salauyou Avatar answered Oct 03 '22 06:10

Alex Salauyou