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.
Try this:
for(String str: myList) {
if(str.trim().equals("A"))
return true;
}
return false;
You need to use str.equals
or str.equalsIgnoreCase
instead of contains
because contains
in string
works not the same as contains
in List
List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true
You may be able to use an approximate string matching library to do this, e.g. SecondString, but that is almost certainly overkill - just use one of the for-loop answers provided instead.
You can do it in a single line by using regex:
if (myList.toString().matches(".*\\bA\\b.*"))
This code should perform quite well.
BTW, you could build the regex from a variable, like this:
.matches("\\[.*\\b" + word + "\\b.*]")
I added [
and ]
to each end to prevent a false positive match when the search term contains an open/close square bracket at the start/end.
With Java 8 Stream API:
List<String> myList = Arrays.asList(" A", "B ", " C ");
return myList.stream().anyMatch(str -> str.trim().equals("B"));
String search = "A";
for(String s : myList)
if(s.contains(search)) return true;
return false;
This will iterate over each string in the list, and check if it contains the string you're looking for. If it's only spaces you want to trap for, you can do this:
String search = "A";
for(String s : myList)
if(s.replaceAll(" ","").contains(search)) return true;
return false;
which will first replace spaces with empty strings before searching. Additionally, if you just want to trim the string first, you can do:
String search = "A";
for(String s : myList)
if(s.trim().contains(search)) return true;
return false;
You can use your own code. You don't need to use the looping structure, if you don't want to use the looping structure as you said above. Only you have to focus to remove space or trim the String of the list.
If you are using java8 you can simply trim the String using the single line of the code:
myList = myList.stream().map(String :: trim).collect(Collectors.toList());
The importance of the above line is, in the future, you can use a List or set as well. Now you can use your own code:
if(myList.contains("A")){
//true
}else{
// false
}
Source: Stackoverflow.com