[英]Casting 2d Array to List of lists in Java
So, this might be a simple question, but I wasn't able to find any easy or elegant way to do this.所以,这可能是一个简单的问题,但我找不到任何简单或优雅的方法来做到这一点。 Converting an array to a list is trivial in Java
在 Java 中将数组转换为列表是微不足道的
Double[] old = new Double[size];
List<Double> cast = Arrays.asList(old);
But I'm dealing with images currently and I would like the ability to extend this functionality to a 2d array without having to iterate through one dimension of the array appending to a list.但我目前正在处理图像,我希望能够将此功能扩展到二维数组,而不必遍历附加到列表的数组的一维。
Double[][] -> List<List<Double>>
Is basically what I would like to achieve.基本上是我想要实现的。 I have a solution along the lines of:
我有一个解决方案:
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]));
}
I would like something better and potentially faster than this.我想要比这更好并且可能更快的东西。
The only faster way to do this would be with a fancier view;唯一更快的方法是使用更高级的视图; you could do this with Guava like so:
你可以像这样用番石榴做到这一点:
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);
}
}
}
That returns a view in constant time.这会在恒定时间内返回一个视图。
Short of that, you already have the best solution.除此之外,您已经有了最好的解决方案。
(FWIW, if you do end up using Guava, you could use Doubles.asList(double[])
so you could use a primitive double[][]
instead of a boxed Double[][]
.) (FWIW,如果你最终使用番石榴,你可以使用
Doubles.asList(double[])
所以你可以使用原始double[][]
而不是盒装Double[][]
。)
After JAVA 8 stream APIs
we can get the list of lists from 2d array in a much faster and cleaner way.在
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());
作为 Java8,你做Arrays.stream(array).map(Arrays::asList).collect(Collectors.toList())
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.