【问题标题】:Casting 2d Array to List of lists in Java将 2d 数组转换为 Java 中的列表列表
【发布时间】:2013-04-25 04:45:05
【问题描述】:

所以,这可能是一个简单的问题,但我找不到任何简单或优雅的方法来做到这一点。在 Java 中将数组转换为列表很简单

Double[] old = new Double[size];
List<Double> cast = Arrays.asList(old);

但我目前正在处理图像,我希望能够将此功能扩展到二维数组,而不必遍历附加到列表的数组的一维。

Double[][] -> List<List<Double>>

基本上是我想要实现的。我有一个解决方案:

Double[][] old= new Double[width][height];
List<List<Double>> new= new ArrayList<List<Double>>();
for (int i=0;i<old.length();i++){
    new.add(Arrays.asList(old[i]));
}

我想要比这更好并且可能更快的东西。

【问题讨论】:

  • 你必须使用嵌套的for循环。
  • 您有解决方案。真的没有比这更快的方法了。
  • 每个人都想避免循环......最终你或一些图书馆必须使用一个。
  • 为什么不混合两者? List:没有自动装箱 ==> 更好的性能

标签: java list data-structures multidimensional-array


【解决方案1】:

唯一更快的方法是使用更漂亮的视图;你可以像这样使用Guava 做到这一点:

Double[][] array;
List<List<Double>> list = Lists.transform(Arrays.asList(array),
  new Function<Double[], List<Double>>() {
    @Override public List<Double> apply(Double[] row) {
      return Arrays.asList(row);
    }
  }
}

以恒定时间返回视图。

除此之外,您已经有了最好的解决方案。

(FWIW,如果你最终使用 Guava,你可以使用 Doubles.asList(double[]),这样你就可以使用原始的 double[][] 而不是盒装的 Double[][]。)

【讨论】:

    【解决方案2】:

    作为 Java8 你做Arrays.stream(array).map(Arrays::asList).collect(Collectors.toList())

    【讨论】:

      【解决方案3】:

      JAVA 8 stream APIs 之后,我们可以以更快、更简洁的方式从二维数组中获取列表列表。

      Double[][] old= new Double[width][height];
      List<List<Double>> listOfLists = Arrays.stream(Objects.requireNonNull(old)).map(row -> {
              return Arrays.asList((row != null) ? row : new Double[0]);
          }).collect(Collectors.toList());
      

      【讨论】:

        猜你喜欢
        • 2022-08-03
        • 2019-06-11
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 2016-03-25
        • 2022-11-03
        • 1970-01-01
        相关资源
        最近更新 更多