DVK
DVK

Reputation: 129549

What's the most elegant/idiomatic way to check if a string is in a list?

In Java, what's the most elegant/idiomatic way to check if a string is in a list?

E.g., if I have String searchString = "abc"; List<String> myList = ...., what's Java's equivalent to what I would do in Perl as:

my $isStringInList = grep { /^$searchString$/ } @myList;
# or in Perl 5.10+
my $isStringInList = $searchString ~~ @myList;

?

Upvotes: 1

Views: 143

Answers (2)

Juned Ahsan
Juned Ahsan

Reputation: 68715

You can use List contains method to check whether the string is present or not in the list:

public boolean contains(Object o)

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

Simply use it like this:

myList.contains(searchString);

Upvotes: 7

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85799

You're looking for Collection#contains method, since List inherits this method from Collection interface. From its Javadoc:

boolean contains(Object o)

Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

It is very simple to use:

String searchString = "abc";
List<String> myList = .... //create the list as you want/need
if (myList.contains(searchString)) {
    //do something
} else {
    //do something else
}

Note that this won't support a insensitive search i.e. you can have "abc" in the list but doesn't mean you will get the same if seeking for "aBc". If you want/need this, you will have to write your own method and use an iterator.

Upvotes: 1

Related Questions