In this Q&A, we'll go over how to iterate over a HashMap or HashSet in consistent order.
Hash collection does not guarantee the iteration order. It also does not guarantee that the iteration order will stay constant over time.
But, Java collection framework provides two classes LinkedHashSet and LinkedHashMap that solves this problem. You can use these classes to look up based on a key and also to iterate over the collection in order.
By default, iteration order is the insertion order. Object can be constructed with an iteration mode argument to change the order from insertion-order to access order.
Sample usage:
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class LHMTest {
public static void main(String[] args) {
HashMap<Integer, Integer> lhm = new LinkedHashMap<>();
for(int i=0; i < 1000; ++i)
lhm.put(i, i );
// key based lookup
assert( lhm.get(100) == 100 );
// print in order of insertion
//lhm.forEach((Integer k, Integer v) -> System.out.println(k));
Iterator<Map.Entry<Integer, Integer>> it = lhm.entrySet().iterator();
int i = 0;
while(it.hasNext()) {
Integer k = it.next().getKey();
assert ( k == i++);
}
}
}
Comments
Post a Comment