Reputation: 159
My requirement is comparing String
to ArrayList
which contains a list of strings. Can any one suggest me?
Upvotes: 14
Views: 139692
Reputation: 1
Convert your Array to Array list first
List al = Arrays.asList("Your Array");
Then compare using contains or equals
if (al.contains("Your String") {
// Code
}
Upvotes: 0
Reputation: 934
This is your method:
private boolean containsString(String testString, ArrayList<String> list)
{
return list.contains(testString);
}
Upvotes: 8
Reputation:
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
Upvotes: 4
Reputation: 29806
If you are willing to use Lambdaj, then check the presence of the String as:
private boolean isContains(ArrayList<String> 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));
Upvotes: 3
Reputation: 38168
There are different options you could consider :
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
Upvotes: 4
Reputation: 2505
Use
ArrayList.contains("StringToBeChecked");
If the String is present in the ArrayList, this function will return true, else will return false.
Upvotes: 22
Reputation: 424983
Look at the List#contains(T obj) method, like this:
List<String> list = new ArrayList<String>();
list.add("abc");
list.add("xyz");
list.contains("abc"); // true
list.contains("foo"); // false
Upvotes: 8