g_rmz g_rmz - 5 months ago 13
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
isIn()
-like boolean function that scans
list_name
in order to find
var_name
?

Answer

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
}

List#contains

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.