Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hashmaps without the value?

Let's say I want to put words in a data structure and I want to have constant time lookups to see if the word is in this data structure. All I want to do is to see if the word exists. Would I use a HashMap (containsKey()) for this? HashMaps use key->value pairings, but in my case I don't have a value. Of course I could use null for the value, but even null takes space. It seems like there ought to be a better data structure for this application.

The collection could potentially be used by multiple threads, but since the objects contained by the collection would not change, I do not think I have a synchronization/concurrency requirement.

Can anyone help me out?

like image 244
jbu Avatar asked May 13 '09 00:05

jbu


People also ask

Can HashMap have empty values?

It is thread-safe and can be shared with many threads. HashMap allows one null key and multiple null values whereas Hashtable doesn't allow any null key or value.

Can HashMap have empty key?

HashMap and LinkedHashMap allows null keys and null values but TreeMap doesn't allow any null key or value. Map can't be traversed so you need to convert it into Set using keySet() or entrySet() method.

How do I find the value of a map without a key?

Check out the Map. entrySet() and Map. values() methods; those provide access to all values without having to provide a key.

Can Java map have null values?

Values entered in a map can be null .


1 Answers

Use HashSet instead. It's a hash implementation of Set, which is used primarily for exactly what you describe (an unordered set of items).

like image 161
Dan Lew Avatar answered Sep 23 '22 15:09

Dan Lew