5

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?

g_rmz
  • 721
  • 2
  • 8
  • 20

4 Answers4

12

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.

Community
  • 1
  • 1
Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
  • 2
    If the collections is more than a few elements, a more efficient alternative might be to use a Set instead of a List but then you would use Set.contains. + 1 – Peter Lawrey Jul 04 '16 at 10:37
  • 1
    it's important to implement equals if List is using any custom object – Gaurava Agarwal Jul 04 '16 at 10:39
  • Thank you! @GauravaAgarwal what do you mean? – g_rmz Jul 04 '16 at 10:44
  • 1
    @GauravaAgarwal, yes, it is. And every time you override `equals()` you should override `hashCode()` as well to make your class hash-based collections compatible. See J. Bloch's "Effective Java" 2nd edition, Item 9 – Vladimir Vagaytsev Jul 04 '16 at 10:44
3

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.

Gaurava Agarwal
  • 974
  • 1
  • 9
  • 32
2

The java.util.ArrayList.contains(Object) method returns true if this list contains the specified element.

List list=new ArrayList();
list.add(1);
list.add(2); 
if(list.contains(2)){
//do something 
}
Keshav
  • 821
  • 2
  • 12
  • 33
1

the contains method of the list data structure is what you're after. You can use this in 1 of two ways:

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

or

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

as in Yasin's answer.

For further info refer to either tutorial point or the official documentation

Crypteya
  • 147
  • 11