Can anybody tell me the reason why HashMap
doesn't implement the Iterable
interface?
-
To iterate over what? Keys? Values? Map.Entry items? – user207421 Oct 17 '13 at 09:10
-
1possible duplicate of [Why can't we use Iterator on a Map(Java)?](http://stackoverflow.com/questions/11507794/why-cant-we-use-iterator-on-a-mapjava) – RAS Oct 17 '13 at 09:11
-
@GaborSch The point is that that is not the only choice. The OP might well have another opinion. – user207421 Oct 17 '13 at 09:16
-
2"Put on hold as primarily opinion-based by ... Boann". [No I didn't.](http://meta.stackexchange.com/questions/54917/distinguish-votes-to-close-by-reason) – Boann Oct 17 '13 at 15:31
-
Obviously should iterate on entries by default; the fact that Java does not make Map iterable is totally retarded, no offense to anyone except whomever at Sun/Oracle decided on this lol. – Alexander Mills Feb 17 '19 at 07:12
6 Answers
To be blunt, Map
in general (and HashMap
in particular) do not implement Iterator
because it is not clear what it should be iterating. There are three choices:
- Keys
- Values
- Entries
None of the three choices above look entirely unreasonable: an argument can be made in favor of each of these approaches. In the end, the library designers decided not to make this choice for you, letting programmers pick what to iterate explicitly.

- 714,442
- 84
- 1,110
- 1,523
Map doesn't implement it but you can use keySet()
or values()
or entrySet()
and all implement iterator as they are sets. See Map javadoc here

- 5,542
- 9
- 54
- 80
-
4
-
2That's true, but it does tell how to work around it, which is useful. – Freedom_Ben Jul 11 '18 at 21:14
Hash map contains two data structures, keys and values, and each of them has an iterator. HashMap as a whole is not a data structure that you should iterate over.

- 10,519
- 8
- 40
- 45
Not directly. You need a 1 dimension structure to iterate it.
hashMap.entrySet().iterator()
will do the job.

- 4,897
- 4
- 18
- 26
Sun could have made Map extend Iterable, but that would require that Map itself should have an iterator() method. Imagine all the custom Map implementations that would be broken. It's bad enough they did that with the java.sql interfaces.
Besides, you can iterate over the map by using keySet(), entrySet() or values() - that's 8, 10 or 8 extra characters.

- 3,381
- 5
- 47
- 90
Map interface does not implement Collection interface, because it does not contain elements but contains entries of keys and their corresponding values.