In Java, I want to check whether a String exists in a List myList.
Something like this:
if(myList.contains("A")){
//true
}else{
// false
}
The problem is myList can contain un-trimmed data:
{' A', 'B ', ' C '}
I want it to return true if my item 'B' is in the list. How should I do this? I would like to avoid a looping structure.
解决方案
You need to iterate your list and call String#trim for searching:
String search = "A";
for(String str: myList) {
if(str.trim().contains(search))
return true;
}
return false;
OR if you want to fo ignore case search, use:
search = search.toLowerCase(); // outside loop
// inside the loop
if(str.trim().toLowerCase().contains(search))