[java] One liner to check if element is in the list

I have been working on and off with Java/Python. Now in this situation I want to check if the element is in the list and do stuff...

Python says:

if "a" in ["a", "b", "c"]:
    print "It's there!"

Does java provide any one liner for this rather than creating ArrayList / Set or similar data structure in steps and adding elements to it?

Thanks

This question is related to java

The answer is


Use Arrays.asList:

if( Arrays.asList("a","b","c").contains("a") )

You can use java.util.Arrays.binarySearch to find an element in an array or to check for its existence:

import java.util.Arrays;
...

char[] array = new char[] {'a', 'x', 'm'};
Arrays.sort(array); 
if (Arrays.binarySearch(array, 'm') >= 0) {
    System.out.println("Yes, m is there");
}

Be aware that for binarySearch to work correctly, the array needs to be sorted. Hence the call to Arrays.sort() in the example. If your data is already sorted, you don't need to do that. Thus, this isn't strictly a one-liner if you need to sort your array first. Unfortunately, Arrays.sort() does not return a reference to the array - thus it is not possible to combine sort and binarySearch (i.e. Arrays.binarySearch(Arrays.sort(myArray), key)) does not work).

If you can afford the extra allocation, using Arrays.asList() seems cleaner.


I would use:

if (Stream.of("a","b","c").anyMatch("a"::equals)) {
    //Code to execute
};

or:

Stream.of("a","b","c")
    .filter("a"::equals)
    .findAny()
    .ifPresent(ignore -> /*Code to execute*/);

You could try using Strings with a separator which does not appear in any element.

if ("|a|b|c|".contains("|a|"))

If he really wants a one liner without any collections, OK, he can have one:

for(String s:new String[]{"a", "b", "c")) if (s.equals("a")) System.out.println("It's there");

*smile*

(Isn't it ugly? Please, don't use it in real code)


In JDK7:

if ({"a", "b", "c"}.contains("a")) {

Assuming the Project Coin collections literals project goes through.

Edit: It didn't.


There is a boolean contains(Object obj) method within the List interface.

You should be able to say:

if (list.contains("a")) {
    System.out.println("It's there");
}

According to the javadoc:

boolean contains(Object o)

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).


 public class Itemfound{ 
        public static void main(String args[]){

                if( Arrays.asList("a","b","c").contains("a"){
                      System.out.println("It is here");
         }
    }

}

This is what you looking for. The contains() method simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.

public boolean contains(Object o) {
return indexOf(o) >= 0;
}