[英]Reassign all ints with a specific value in 2d array Java
Supppose I have a 2d array, grid defined like so:假设我有一个二维数组,网格定义如下:
int[][] x = new int[][]{{0,0,1},{0,0,2},{0,0,3}};
Now suppose I want to reassign all positions in the grid with value 0 to Integer.MAX_VALUE现在假设我想将网格中值为 0 的所有位置重新分配给 Integer.MAX_VALUE
I can do this in Java 10:我可以在 Java 10 中做到这一点:
for(var row : grid)
for(int i=0; i<row.length; i++)
if(row[i] ==0) row[i]=Integer.MAX_VALUE;
Is there a way I can make this shorter without creating a new array?有没有办法可以在不创建新数组的情况下缩短它? I know I can use streams, but won't that create a new array, wasting memory?
我知道我可以使用流,但不会创建一个新数组,浪费 memory?
Just took a look at the Java 10 docs Arrays class to see what it might have to offer.只需查看 Java 10 文档Arrays class 看看它可能提供什么。
for(var row : arrayOfArrays)
Arrays.setAll(row, i -> row[i] == 0 ? Integer.MAX_VALUE : row[i]);
Would only be helpful for removing one line, and is only applicable to inner loop.仅有助于删除一行,并且仅适用于内部循环。
Note that List<E>
has a forEach(Consumer<E>)
method (implemented from Iterable<E>
) so you would be able to use forEach
for the outer loop.请注意,
List<E>
有一个forEach(Consumer<E>)
方法(从Iterable<E>
实现),因此您可以将forEach
用于外部循环。 However I was incorrect when I said you could try List<List<int>>
because you would not be able to set the variable using the consumer variable.但是,当我说您可以尝试
List<List<int>>
时,我是不正确的,因为您将无法使用消费者变量来设置变量。 You could still do List<int[]>
and then try the following.您仍然可以执行
List<int[]>
然后尝试以下操作。
List<int[]> listOfArrays = new ArrayList<>();
//Fill in values
listOfArrays.forEach(inner -> Arrays.setAll(inner, i -> inner[i] == 0 ? Integer.MAX_VALUE : inner[i]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.