JAVA: Including an alternative (||) in a loop?

I have a quick question. I want my code to be shorter, and I wonder if it is possible to set checkboxes in a loop in any way. The meaning of this part of the code is to enable the "Find" button when at least one of the checkboxes is selected. Thank you in advance for every tip.

    if (checkBoxes[0].isSelected() == true || checkBoxes[1].isSelected() == true
            || checkBoxes[2].isSelected() == true || checkBoxes[3].isSelected() == true || checkBoxes[4].isSelected() == true
            || checkBoxes[5].isSelected() == true || checkBoxes[6].isSelected() == true || checkBoxes[7].isSelected() == true
            || checkBoxes[8].isSelected() == true || checkBoxes[9].isSelected() == true || checkBoxes[10].isSelected() == true
            || checkBoxes[11].isSelected() == true || checkBoxes[12].isSelected() == true || checkBoxes[13].isSelected() == true
            || checkBoxes[14].isSelected() == true || checkBoxes[15].isSelected() == true || checkBoxes[16].isSelected() == true
            || checkBoxes[17].isSelected() == true || checkBoxes[18].isSelected() == true || checkBoxes[19].isSelected() == true
            || checkBoxes[20].isSelected() == true || checkBoxes[21].isSelected() == true) {
        button.setEnabled(true);
+4
source share
5 answers

try the following:

for(int i=0; i < checkBoxes.length; i++) {
    if(checkBoxes[i].isSelected()) {
        button.setEnabled(true);
        break;
    }
}
+2
source

Of course you can:

boolean found = false;
for (int i = 0; i < checkBoxes.length && !found; i++) {
    found = checkBoxes[i].isSelected();
}
if (found) {
    button.setEnabled(true);
}

or you can escape the variable booleanand exit the loop when you find the first checkbox selected:

for (int i = 0; i < checkBoxes.length; i++) { // you can also replace this with enhanced
                                              // for loop
    if (checkBoxes[i].isSelected()) {
        button.setEnabled(true);
        break;
    }
}
+6
source

stream?

if (Arrays.stream(checkBoxes).anyMatch(checkbox -> checkbox.isSelected())) {
    button.setEnabled(true);
}
+6

, , .

:

for (Checkbox checkBox : checkBoxes){
   if (checkBox.isSelected()){
      button.setEnabled(true);
      break;
   }
}
+3
Boolean j = false;
for (byte i = 0; i <= 21)
    if (checkBoxes[i].isSelected() == true) {
        j = true;
        break;
        if (j == true) {
            //your code
        }

you use this code it's that simple

-1
source

Source: https://habr.com/ru/post/1672234/


All Articles