if item *in* array java

Viewed 233

I'm a python programmer who is learning java

I ran across the following problem (or maybe complication is a better term to use)

In python, I can easily check if an item is in a list within an if statement like so:

x = 1
if x in [0,1,2,3,4,5]:
    #do something

what is the easiest way to do that in java?

  • can I do it without using a list variable like in the example above?

e.g

{0,1}.contains(1)

(not sure if this is a duplicate, I did look, if it is be sure to flag it for =)

3 Answers

Try this:

if (Arrays.asList(array).contains("---something---"))

Another method may help you.

If the array element is consecutive sequenceuse:

int x = 1;
if (IntStream.range(0, 6).anyMatch(value -> value == x)) {
    // do something like print message
    System.out.println("find x");
}

If the element of array is non-contiguous sequence:

int x = 1;
int[] inputs = new int[] {0, 1, 2, 3, 4, 5, 8, 9, 10};
if (Arrays.stream(inputs).anyMatch(value -> value == x)) {
    // do something like print message
    System.out.println("find x");
}

Here I use arrays, that means once u create a arrays u cant change his size, Then I parse the arrays with a for loop and check if my values x is equals to my values in myArrays in the iteration i of the loop.

public static void main(String[] args) {
        int x = 2;
        int [] myArray = {1,2,3,4,5};
        for (int i = 0; i < myArray.length; i++) {
            if(x == myArray[i])
            {
                //do something
            }
        }   
    }
}
Related