Operator in in java

4

I'm learning Java and I came across the need for the in operator. For example:

I have a vector ( v = {1,2,3,4,6} ) and I want to see if the 5 is in this vector (not in this case).

In python it would be v = [1,2,3,4,6] - 6 in v , then it would return False . I want to do this in Java, but do not find the operator that works.

How do I do this in java?

    
asked by anonymous 10.09.2017 / 03:15

2 answers

6

Using java-8, you can verify through the API Streams :

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 5);

See a test on ideone

Without using streams, this is also possible:

public static void main (String[] args)
{
    int[] number = {1, 2, 3, 4};

    if(contains(number, 5)){
        System.out.println("Contem o numero 5");
    }else {
        System.out.println("Nao contem o numero 5");
    }
}

public static boolean contains(final int[] array, final int v) {

    boolean result = false;

    for(int i : array){
        if(i == v){
            result = true;
            break;
        }
    }

    return result;
}

Also working on ideone .

References:

10.09.2017 / 03:18
6

This operator you are looking for is the contains ". The purpose of it is exactly the one you want.

If you change your array by a Set or List and the solution is simple. For this, you can use the asList to turn your array into a list:

List<Integer> lista = Arrays.asList(1, 2, 3, 4, 6);
System.out.println(lista.contains(5)); // false
System.out.println(lista.contains(4)); // true

See here working on ideone.

    
10.09.2017 / 03:57