Doubling a Matrix

前端 未结 3 753
后悔当初
后悔当初 2021-01-26 08:21

I\'ve created a two dimensional matrix and populated it with random numbers. I\'ve then printed it out. I need help creating a second matrix that is twice the size of the first,

3条回答
  •  清酒与你
    2021-01-26 08:36

    In Java 8 you can handle this pretty easily using maps and collectors. Here is a full example:

    public class DoubleMatrix {
      public static void main(String[] args) {
        List> startingMatrix = Arrays.asList(
            Arrays.asList(3, 4),
            Arrays.asList(2, 1)
        );
    
        List> doubleMatrix
            = startingMatrix.stream()
                            .map(innerList -> { //For each list
                              List doubled = innerList.stream()
                                                               .map(element -> Arrays.asList(element, element)) //Return a list doubling each element
                                                               .flatMap(l -> l.stream())  //Flatten out/join all doubled lists
                                                               .collect(Collectors.toList());
                              return Arrays.asList(doubled, doubled); //Double the list
                            })
                            .flatMap(l -> l.stream())
                            .collect(Collectors.toList()); //Collect into a final list
    
        System.out.println(doubleMatrix);
      }
    }
    

    This avoids needing to know the size of the list beforehand, and is also tolerant of there being a difference between the width and height of your matrix - simply doubling every element in both directions.

提交回复
热议问题