In Java, I want to check whether a String exists in a List<String> 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.
contains() in Java. ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
The trimToSize() method of ArrayList in Java trims the capacity of an ArrayList instance to be the list's current size. This method is used to trim an ArrayList instance to the number of elements it contains. Parameter: It does not accepts any parameter. Return Value: It does not returns any value.
With Java 8 Stream API:
List<String> myList = Arrays.asList(" A", "B ", " C "); return myList.stream().anyMatch(str -> str.trim().equals("B"));
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 perform ignore case search, then use:
search = search.toLowerCase(); // outside loop // inside the loop if(str.trim().toLowerCase().contains(search))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With