Gaussia
Gaussia

Reputation: 143

Appropriate storage of objects for easy lookup (Java)

I have a file with a list of Strings. The input to my program will be new strings and I need a good way to check whenever the input string occurs within my predetermined list of strings (this is a part of a larger program which will make a lot of request for whenever certain string are in my predetermined list or not.

Basically I have a set of Strings and I want to check whenever a new String is in that set in O(1) time. What I have used now is to create a HashMap<String,Boolean>, and stores all my predetermined strings in that with the Boolean true attached. I can then check whenever the string s is in my predetermined set by containsKey(s)

However, this feels wrong in the sense that a hash map is meant to do more than what I want (pair an input with an output) and here I am only using the containsKey(String string) function. Also, I am essentially storing a lot of Boolean which I do not need. But this was the only way I could come up with in O(1) time.

Is there a better way of doing what I want to do?

Cheers

Upvotes: 0

Views: 61

Answers (1)

Turamarth
Turamarth

Reputation: 2282

Simply use a HashSet<String>. You can then check it similarly to your HashMap with contains(s).

Upvotes: 2

Related Questions