Java, return if trimmed String in List contains String

后端 未结 7 2354
旧巷少年郎
旧巷少年郎 2020-12-04 17:52

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

Something like this:

if(myList.contains(\"A\")){
    //         


        
7条回答
  •  -上瘾入骨i
    2020-12-04 18:02

    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.

提交回复
热议问题