Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 803
g_rmz Avatar asked Jul 04 '16 10:07

g_rmz


2 Answers

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

if (listName.contains(varName)) {
    // 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.

  • Why do I need to override the equals and hashcode methods in Java ?
like image 62
Yassin Hajaj Avatar answered Oct 04 '22 23:10

Yassin Hajaj


You can use List.contains(object), but make sure your class which you have used to create list, is implementing equals for proper equals check. Otherwise you will be able to only get two objects equal only if object itself is same.

like image 36
Gaurava Agarwal Avatar answered Oct 04 '22 22:10

Gaurava Agarwal