Java, return if trimmed String in List contains String


In Java, I want to check whether a String exists in a List<String> myList.

Something like this:

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

This question is tagged with java arrays string list

~ Asked on 2013-04-25 15:29:48

The Best Answer is


You need to iterate your list and call String#trim for searching:

String search = "A";
for(String str: myList) {
       return true;
return false;

OR if you want to perform ignore case search, then use:

search = search.toLowerCase(); // outside loop

// inside the loop

~ Answered on 2013-04-25 15:33:28


With Java 8 Stream API:

List<String> myList = Arrays.asList("  A", "B  ", "  C  ");
return -> str.trim().equals("B"));

~ Answered on 2015-11-06 01:41:56

Most Viewed Questions: