Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

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.

like image 203
RaceBase Avatar asked Apr 25 '13 15:04

RaceBase


People also ask

How do you check if a string is present in a list of strings in Java?

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.

How do you trim a string list in Java?

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.


2 Answers

With Java 8 Stream API:

List<String> myList = Arrays.asList("  A", "B  ", "  C  "); return myList.stream().anyMatch(str -> str.trim().equals("B")); 
like image 157
rogermenezes Avatar answered Sep 21 '22 15:09

rogermenezes


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)) 
like image 30
anubhava Avatar answered Sep 20 '22 15:09

anubhava