0

One can iterate through a SortedMap by using the iterator from myMap.entrySet().iterator(). But does this iterator preserve the ordering of the sorted map object ?

The SortedMap interface does not have its own methods to iterate through the entries. What is the standard way to iterate ordered through the entries?

Jegs
  • 1
  • 5
  • Set does not preserve order, only lists preserve order. – hamid Dec 21 '13 at 19:12
  • 3
    @Sam The `Set` returned by `SortedMap#entrySet()` has an ordering. – Sotirios Delimanolis Dec 21 '13 at 19:13
  • 1
    Sam, that's not entirely correct. The Set interface does not imply any iteration order of its subclasses, but implementers of SortedSet do imply a sorted iteration order. Please see http://docs.oracle.com/javase/7/docs/api/java/util/SortedSet.html for more – whaley Dec 21 '13 at 19:14

2 Answers2

1

One can iterate through a SortedMap by using the iterator from myMap.entrySet().iterator(). But does this iterator preserve the ordering of the sorted map object ?

Yes. See the javadocs for SortedMap:

This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods).


The SortedMap interface has no own methods to iterate through the entries. What is the standard way to iterate ordered through the entries ?

The usual trick is to use entrySet(), and iterate on those Map.Entry objects. For instance:

for (Map.Entry<K,V> entry : theMap.entrySet()) {
    K entryKey = entry.getKey();
    V entryValue = entry.getValue();
    // do whatever with them
}
yshavit
  • 42,327
  • 7
  • 87
  • 124
0

To answer your main question, yes. Iterating via the entrySet will preserve order.

You can use the Java enhanced foreach loop:

for(final Entry<K,V> entry : myMap.entrySet(()) {
    //do something with entry
}
Boris the Spider
  • 59,842
  • 6
  • 106
  • 166