简体   繁体   中英

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?

Eg, if I have String searchString = "abc"; List<String> myList = .... 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;

?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM