How can I compare String value with ArrayList of String type in Java?

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

My requirement is comparing String to ArrayList which contains a list of strings. Can any one suggest me?

回答1:

Use

ArrayList.contains("StringToBeChecked");

If the String is present in the ArrayList, this function will return true, else will return false.



回答2:

Look at the List#contains(T obj) method, like this:

List list = new ArrayList(); list.add("abc"); list.add("xyz"); list.contains("abc"); // true list.contains("foo"); // false


回答3:

This is your method:

   private boolean containsString(String testString, ArrayList list)     {         return list.contains(testString);    }


回答4:

ArrayList can contain one or more Strings. You cannot compare String with ArrayList. But you can check whether the ArrayList contains that String ot not using contains() method

String str = //the string which you want to compare ArrayList myArray =// my array list boolean isStringExists = myArray.contains(str);// returns true if the array list contains string value as specified by user


回答5:

There are different options you could consider :

  • a simple for each loop using equals on each member of your list to compare it to string A.
  • sorting all strings in list in order to boost up comparison and find if a string in the list matches A.
  • using a sortedSet to achieve the above
  • putting alls string in the intern string pool using intern method on every item in the list and on string A. This will allow to compare strings using == and not equal anymore. Comparison would then be much faster.
  • using a hashmap to achieve better comparison speeds
  • an identity hashmap to mix the two preceding strategies.

Well, the are pros and cons to those methods, it all depends on what you want to do and why and how you compare strings.

Regards, Stéphane



回答6:

If you are willing to use Lambdaj, then check the presence of the String as:

private boolean isContains(ArrayList listOfStrings, String testString) {     return (Lambda.select(listOfStrings, Matchers.equalTo(testString)).size() != 0);   }

Using static import of select and equalTo increase the readability:

select(listOfStrings, equalTo(testString));


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!