Home
Blog
Choosing Between HashMap and HashSet
Updated
Dot Net Perls

Choosing Between HashMap and HashSet

Most programming languages have types like HashMap (also known as Dictionary, Hashtable or map) and HashSet (also known as set). The map types can store both a key and a value, and the set types just store a key. No duplicate keys are allowed—these collections check for uniqueness.

It seems like it is common sense to do certain things with a map, and other things with a set. But is this really necessary? It is possible to do everything with just the map types, and never use the set types. We can just use any value—like a bool with the value true, or the integer 1.

In any case, we typically use sets when:

No values are associated with the keys we are adding.
We are just testing for unique keys.
Set operations, like Intersect or Overlaps are required.

In my experience, normal programs rarely require mathematical set operations. And it makes about as much sense just to use true to indicate a value instead of using an entirely different type like HashSet. There is no likely performance impact. If we are using a Dictionary elsewhere, it may reduce code size to reuse that class for set operations, however.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen