Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to implement a String Array "is in" method using Java

I have a requirement to present highly structured information picked from a highly un-structured web service. In order to display the info correctly, I have to do a lot of String matches and duplicate removals to ensure I'm picking the right combination of elements.

One of my challenges involves determining if a String is in an Array of Strings.

My dream is to do "searchString.isIn(stringArray);" but I realize the String class doesn't provide for that.

Is there a more efficient way of doing this beyond this stub?:

private boolean isIn(String searchString, String[] searchArray)
{
  for(String singleString : searchArray)
  {
    if (singleString.equals(searchString)
      return true;
  }

  return false;
}

Thanks!

like image 443
IVR Avenger Avatar asked Feb 24 '11 16:02

IVR Avenger


1 Answers

You may want to look into HashMap or HashSet, both of which give constant time retrieval, and it's as easy as going:

hashSet.contains(searchString)

Additionally, HashSet (and HashMap for its keys) prevents duplicate elements.

If you need to keep them in order of insertion, you can look into their Linked counterparts, and if you need to keep them sorted, TreeSet and TreeMap can help (note, however, that the TreeSet and TreeMap do not provide constant time retrieval).

like image 69
Zach L Avatar answered Sep 19 '22 18:09

Zach L