Simulate if-in statement in Java

I have coded several months in Python, and now I need to switch to Java for work related reasons. My question is, is there a way to mimic this type of expression

if var_name in list_name:
    # do something

without defining an extra isIn()-like boolean function that scans list_nameto find var_name?

+4
source share
4 answers

You are looking for List#containsone that is inherited from Collection#contains(so you can use it with objects too Set)

if (listName.contains(varName)) {
    // doSomething
}

List#contains

true, . , true , e , (o == null? e == null: o.equals(e)).

, List#contains equals true false. , , hashcode.

+12

List.contains(object), , , , . , .

+3

java.util.ArrayList.contains(Object) true, .

List list=new ArrayList();
list.add(1);
list.add(2); 
if(list.contains(2)){
//do something 
}
+2

contains - , . :

boolean return_flag = list_name.contains(var_name)
if return_flag{
    //do stuff
}

if list_name.contains(var_name){
   //do stuff
}

.

.

+1

All Articles