Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

One liner to check if element is in the list

Tags:

java

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

like image 814
Vishal Avatar asked Jan 25 '10 20:01

Vishal


People also ask

How do you check if an element is in a list?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do you check if an element is in the list Java?

contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.

How do you check if an element exists in a string?

count() function: This function is used to count the presence of element is the string. We can use this function to check the existence of string in large string. If string exist in string then it return some number else it return 0.

Which operator is used to check if an element is in a list?

“in” operator − This operator is used to check whether an element is present in the passed list or not. Returns true if the element is present in the list otherwise returns false.


1 Answers

Use Arrays.asList:

if( Arrays.asList("a","b","c").contains("a") ) 
like image 82
Mark Elliot Avatar answered Oct 04 '22 11:10

Mark Elliot