Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an Array contains specific term - Android

I currently have a statement which reads

if(Arrays.asList(results).contains("Word"));

and I want to add at least several more terms to the .contains parameter however I am under the impression that it is bad programming practice to have a large number of terms on one line..

My question is, is there a more suitable way to store all the values I want to have in the .contains parameters?

Thanks

like image 545
TomSelleck Avatar asked Mar 24 '12 17:03

TomSelleck


2 Answers

You can use intersection of two lists:

String[] terms = {"Word", "Foo", "Bar"};
List<String> resultList = Arrays.asList(results);
resultList.retainAll(Arrays.asList(terms))
if(resultList.size() > 0)
{
         /// Do something
}

To improve performance though, it's better to use the intersection of two HashSets:

String[] terms = {"Word", "Foo", "Bar"};
Set<String> termSet = new HashSet<String>(Arrays.asList(terms));
Set<String> resultsSet = new HashSet<String>(Arrays.asList(results));
resultsSet.retainAll(termSet);
if(resultsSet.size() > 0)
{
         /// Do something
}

As a side note, the above code checks whether ANY of the terms appear in results. To check that ALL the terms appear in results, you simply make sure the intersection is the same size as your term list:

 resultsSet.retainAll(termSet);
 if(resultSet.size() == termSet.size())
like image 123
Diego Avatar answered Nov 07 '22 13:11

Diego


You can utilize Android's java.util.Collections class to help you with this. In particular, disjoint will be useful:

Returns whether the specified collections have no elements in common.

Here's a code sample that should get you started.

In your Activity or wherever you are checking to see if your results contain a word that you are looking for:

    String[] results = {"dog", "cat"};
    String[] wordsWeAreLookingFor = {"foo", "dog"};
    boolean foundWordInResults = this.checkIfArrayContainsAnyStringsInAnotherArray(results, wordsWeAreLookingFor);
    Log.d("MyActivity", "foundWordInResults:" + foundWordInResults);

Also in your the same class, or perhaps a utility class:

private boolean checkIfArrayContainsAnyStringsInAnotherArray(String[] results, String[] wordsWeAreLookingFor) {
    List<String> resultsList = Arrays.asList(results);
    List<String> wordsWeAreLookingForList = Arrays.asList(wordsWeAreLookingFor);
    return !Collections.disjoint(resultsList, wordsWeAreLookingForList);
}

Note that this particular code sample will have contain true in foundWordInResults since "dog" is in both results and wordsWeAreLookingFor.

like image 30
louielouie Avatar answered Nov 07 '22 11:11

louielouie