[英]How to do list comprehension in Java
I'm writing a program and I want to shorten the code through list comprehension (like those in Python). 我正在编写一个程序,并且想通过列表理解(如Python中的代码)来缩短代码。 However, I faced syntax errors while trying to simplify the code:
但是,在尝试简化代码时遇到语法错误:
I've attempted to troubleshoot this problem multiple times, but all the solutions they proposed are through ArrayLists while I want to complete this task in the form of an integer array (int[]). 我已经尝试多次解决此问题,但是当我想以整数数组(int [])的形式完成此任务时,他们提出的所有解决方案都是通过ArrayLists进行的。
boolean[][] seats;
Theater(int row, int col) {
for (int i=0; i<row; i++) for (int j=0; j<col; j++) seats[i][j] = false;
}
public int[] findSeats(int row) {
int[] arr = [x for (boolean x : this.seats[row]) if (x == false)];
return arr;
}
I expected the code above to work but the following messages showed up instead: 我希望上面的代码能正常工作,但是出现了以下消息:
Syntax error on tokens, delete these tokens
Syntax error on token "]", delete this token
Can anyone please help? 谁能帮忙吗? Much appreciated.
非常感激。
This language construct of Python is not available in Java. Python的这种语言构造在Java中不可用。 I assume you are finding vacant seats in a row?
我认为您连续发现空缺席位? The closest I thought will be something like this
我认为最接近的是这样的
public int[] findSeats(int row) {
final int[] avSeats = new int[seats[row].length];
IntStream.range(0, seats[row].length).filter(seatNo -> !seats[row][seatNo]).forEach(seatNo -> avSeats[seatNo] = 1);
return avSeats;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.