0

In the program I'm writing on, I'll have to check if a List (actually I can replace the type of Collection if necessary) contains a specific String.

Is this the fastest way to do it?

private boolean containsItem(List<String> list, String path) {
        for (String s : list) {
            if (s.equals(path)) {
                return true;
            }
        }
        return false;
}

I'm asking for performance only, as this operation may happen a couple of thousand times in a row.

Jdv
  • 962
  • 10
  • 34
  • 3
    Use a HashSet to improve performance, and instead of your method, use `set.contains(path)`. – Eran Jan 28 '16 at 08:10
  • 1
    not to mention: list.contains(path) would be better suited than this code. – Stultuske Jan 28 '16 at 08:11
  • and contains method of set. – bNd Jan 28 '16 at 08:11
  • @Eran: Well, a `HashSet` will improve *retrieval* performance. But naturally there's a cost in terms of *insert* performance. – T.J. Crowder Jan 28 '16 at 08:14
  • 1
    @T.J.Crowder Well, given that the OP said he wants to run the search for `a couple of thousand times in a row`, I figured it would be more efficient to store the data in a `HashSet`. Of course if inserts happen more often than retrievals, that may not be true. – Eran Jan 28 '16 at 08:18
  • @ParkerHalo: What makes you think the built-in would be *slower* than a manual loop in the code calling it? At worst it'll be a tie. At best the implementation can work directly with the data structures rather than through the API and save a fair bit of work. – T.J. Crowder Jan 28 '16 at 08:27
  • @Eran: Yes. I'm just saying, a HashSet doesn't just magically improve performance. If reads outweigh writes, it will, but that's not the same as a bald "will improve performance" statement. – T.J. Crowder Jan 28 '16 at 08:28
  • Possible duplicate of [Fastest way to check if a List contains a unique String](http://stackoverflow.com/questions/3307549/fastest-way-to-check-if-a-liststring-contains-a-unique-string) – Raedwald Jan 28 '16 at 09:17

1 Answers1

0

If you list is const(unmodifiable or your never change it after construct). You can build that list to a Trie treeTrie, and perform search using the tree. It's fast and can find words(not only extract equal)

javamonk
  • 180
  • 1
  • 7