1

for example I want to do something like this:

package tst;

public class forInif {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5};
        if (for(int i : a) {i == 5;}) {/**/}
    }
}

I know normally I should make a boolean value of this situation by my own, but just in case, is there anyway to do something like that rather than make a boolean value somewhere else?

Tony Chen
  • 183
  • 1
  • 16
  • I hope there is no way to do that. Extract the loop to separate method and do if(myLoopedMethodReturnedTrue()){} – secretwpn Jan 09 '17 at 08:05
  • See here: http://stackoverflow.com/questions/1128723/how-can-i-test-if-an-array-contains-a-certain-value – Tim Biegeleisen Jan 09 '17 at 08:06
  • 1
    There is a one-liner in Java 8 using streams, but other than this you are better off just writing a loop to iterate over the `int[]` array yourself. – Tim Biegeleisen Jan 09 '17 at 08:06
  • What boolean value you expect from a "loop"? How do you imagine it? what it should show? Just use what you already wrote, but other way around: `for(int i : a) {if (i == 5) {/**/ break;}} ` – Ruslan Stelmachenko Jan 09 '17 at 08:10
  • 1
    @TimBiegeleisen There's a one-liner for all Java versions (1.2+), assuming array is sorted like it is in the question: `if (Arrays.binarySearch(a, 5) >= 0) {/**/}` – Andreas Jan 09 '17 at 08:14

3 Answers3

1

In Java 8+, you can use IntStream.anyMatch:

if (IntStream.of(a).anyMatch(i -> i == 5)) { ...
yshavit
  • 42,327
  • 7
  • 87
  • 124
0

Not directly no: the condition check in a Java if needs to be a boolean type. But you could build a function:

public class forInif {
    public static void main(String[] args) {
        int[] a = {1,2,3,4,5};
        if (foo(a)) {/**/}
    }
}

where foo is a function returning a boolean that takes an int[] as a parameter.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
0

There is no way to make a for loop return a boolean value. However, streams sound like a good way to do this in one or two lines:

int[] a = {1,2,3,4,5};
int fives = Arrays.stream(a).filter(e -> e == 5).count();
if (fives > 0) {
    //replace this with whatever you want to do when a five is found
    System.out.println("One or more fives exists in the array");
}
nhouser9
  • 6,730
  • 3
  • 21
  • 42
  • Replacing `count()` with `findAny()` would be better: `if (Arrays.stream(a).filter(e -> e == 5).findAny()) {/**/}` – Andreas Jan 09 '17 at 08:16