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


Solution 1:

Use Arrays.asList:

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

Solution 2:

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)).

Solution 3:

In JDK7:

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

Assuming the Project Coin collections literals project goes through.

Edit: It didn't.

Solution 4:

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

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