You could answer to your own question by reading the javadocs for HashMap
. "Read the javadocs" is an important lesson that every beginner in Java should learn and remember.
In this case, the javadocs will show you 3 methods that could be useful:
- The
keys()
method returns a collection consisting of the keys in the table.
- The
values()
method returns a collection consisting of the values in the table.
- The
entries()
method returns a collection representing the key/value pairs in the table.
You can iterate these collections as any other collection. There are examples in the other answers.
However, I get the impression that your application is multi-threaded. If that is the case the there are two other problems that you need to deal with to make your program reliable:
If two or more threads could use the same object or data structure, they need to take the necessary steps to ensure that they are properly synchronized. If they don't then there is a non-zero probability that some sequence of operations will result in the data structure being put into an inconsistent state, or that one or more threads will see an inconsistent state (due to memory caches, values saved in registers, etc).
If one thread is using one of a HashMap's collection iterators and another adds or removes an entry, then the first one is likely to get a ConcurrentModificationException
.
If you solve the above two problems by locking out all other operations on the HashMap
while your "send to all" operation is going on, you are unintentionally creating a performance bottleneck. Basically, everything else stops until the operation has finished. You get a similar effect (but on a finer scale) if you simply put a synchronization wrapper around the HashMap
.
You need to read and learn about these things. (And there's far too much to explain in a single SO Answer). A simple (but not universal) solution to all 3 problems that probably will work in your use-case it to use a ConcurrentHashMap
instead of a plain HashMap
.