Operator in java

Asked

Viewed 858 times

4

I am learning Java and came across the need of the operator in. For example:

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

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

How do I do this in java?

  • 1

    Need to scan with a loop each input.

2 answers

6

Using java-8, you can check 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, it is also possible this way:

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:

6

This operator you are looking for is the method contains. His purpose is exactly what you want.

If you exchange your array for one Set or List and the solution is simple. For this, you can use the method 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.

  • I think it’s worth pointing out that it doesn’t work with primitives.

  • 1

    @Article If you use int[] v = ...; and Arrays.asList(v);, won’t work anyway. But if you use the asList as varargs, there it works. And with this you take advantage of minimizing the use of the hideous arrays.

  • Very interesting, I didn’t know that detail.

  • Will Ellipsis work because it does autoboxing? I believe it works, but the mechanism that makes it work is strange to me

  • 1

    @Jeffersonquesado Yes. The compiler determines which method Arrays.asList(Object...) is what fits. Then he turns it into Arrays.asList(new Object[] {1, 2, 3, 4, 6}). To convert the numbers into objects, it makes the autoboxing, and the result is Arrays.asList(new Object[] {Integer.valueOf(1), Integer.valueOf(2), Integer.valueOf(3), Integer.valueOf(4), Integer.valueOf(6)}). This example allows us to appreciate the beauty of varargs and autoboxing working together to abstract all this complexity into doing something so simple.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.