g_rmz g_rmz - 7 months ago 31
Java Question

Simulate if-in statement in Java

I've coded for several months in Python, and now i have to switch to Java for work's related reasons. My question is, there is a way to simulate this kind of statement

if var_name in list_name:
# do something

without defining an additional
-like boolean function that scans
in order to find


You're looking for List#contains which is inherited from Collection#contains (so you can use it with Set objects also)

if (list.contains(var)) {
    // doSomething


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

As you see, List#contains uses equals to return true or false. It is strongly recommended to @Override this method in the classes you're creating, along with hashcode.