Time-complexity of all 3 collection view iterators for HashMap (myHashMap.entrySet().iterator().next()
and myHashMap.keySet().iterator().next()
and myHashMap.values().iterator().next()
) is well-documented in javadoc, it is O(n+c) for all those 3 iterators (n is number of mappings, c is capacity that is physical number of buckets in hashtable).
But what about respective 3 iterators of 3 respective TreeMap collection views? Nothing is said in official javadoc. What are their complexities? I did look in SE8 source code but I cannot judge from there.
Try to answer this based on these great comments:
One single next()
call has a totally different time complexity compared with the whole iterating process.
TreeMap in Java is based on Red-Black Tree, which is a balanced binary search tree.
Refer to https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html
Iterating a whole TreeMap should have the same time complexity as traversing the Red-Balck Tree(For pre-order in-order or post-order traveral). So time complexity should be O(n)
where n
is the key(or value, or key-value mapping) count.
For a single next
call, we can do it in O(1)
. If a whole O(n)
time complexity is true, this should be trivial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With