开发者

How do I check whether ArrayList of the associated key contains a string of interest?

开发者 https://www.devze.com 2023-03-02 22:10 出处:网络
I have LinkedHashMap<String,ArrayList<String>> h If I do this: System.out.println(h.get(\"key1\")); it prints out this: [Burger King]

I have LinkedHashMap<String,ArrayList<String>> h

If I do this: System.out.println(h.get("key1")); it prints out this: [Burger King]

But if I do this:

if (h.get("key1").contains("Burger"))
    System.out.println("Key1 contains Burger");

It ignores it. How do I check for a particular string i开发者_JS百科n the ArrayList of the associated key?


ArrayList.contains() Returns true if this list contains the specified element.

In your case it doesn't contain "Burger", but it contains "Burger King", the matching is identical not on subtrings.

To achieve what you want you've to loop on the ArrayList and check each element with String.contains() applied on the String which is defined as "Returns true if and only if this string contains the specified sequence of char values".

If you want also to ignore the case you can apply String.toLowerCase() to your search term and to each element before applying String.contains().


you are testing a list for inclusion of a partial string, which will not work, since the actual values is "Burger King". You need to call contains() on each element of the ArrayList if you want to check for a partial match.


List.contains() looks for an exact matching element.

Do you mean this?

for(String s: results.get("key1")) 
  if(s.contains("Burger"))
    System.out.println("Key1 contains Burger");


You have to iterate over all String objects in the ArrayList<String> and call their contains() method:

boolean containsSubString(final Collection<String> strings, final String searchString) {
  for (String s : strings) {
    if (s.contains(searchString)) {
      return true;
    }
  }
  return false;
}


The List contains the String Burger King and you are looking for the String Burger. Hence no output.

0

精彩评论

暂无评论...
验证码 换一张
取 消