javadictionaryiteratorlinkedhashmap

Get a subset of LinkedHashMap and preserve the order


Unlike HashMap, order matters in LinkedHashMap. And the order here is insertion order.

Let say I have a LinkedHashMap like the following (ordered from the top to bottom, left part is key, right part is value):

1:"One"
2:"Two"
3:"Three"
4:"Four"

Then I have a list of keys, which contains, let's say, (3,1).

What I want to do is to loop through the LinkedHashMap in order and pick out the entries whose key is in the list.

So the result I want to have is (1 is still before 3 because that's the order before filtering):

1:"One"
3:"Three"

Here is my code:

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class SelectCertainEntriesFromLinkedHashMap {
    public static void main(String args[]) {
        Map<Integer,String> linkedHashMap = new LinkedHashMap<Integer,String>();
        linkedHashMap.put(1, "One");
        linkedHashMap.put(2, "Twe");
        linkedHashMap.put(3, "Three");
        linkedHashMap.put(4, "Four");
        
        List<Integer> list = new ArrayList<Integer>();
        list.add(3);
        list.add(1);
        
        Map<Integer,String> selectedlinkedHashMap = new LinkedHashMap<Integer,String>();
        
        //will this iterator iterate the keys in the order of the map (1, 2, 3, 4)? Or just random order?
        Iterator<Integer> itr = linkedHashMap.keySet().iterator();
        while(itr.hasNext()) {
            Integer key = itr.next();
            if (list.contains(key)) {
                selectedlinkedHashMap.put(key, linkedHashMap.get(key));
                System.out.println(key + ":" + linkedHashMap.get(key));
            }
        }
    
}

The above code return the result I like. But I am not sure if it is guaranteed.

1:"One"
3:"Three"

The question is:

Iterator<Integer> itr = linkedHashMap.keySet().iterator();

The above line will get a iterator from a set and Set is not ordered. So will this cause the keys in random order? if yes, I can't keep the original order (not guaranteed) of my map after filtering…

Could anybody help me with this?


Solution

  • The iterator returned from keySet().iterator() should return an ordered Set. Documentation from the Map API:

    The Map interface provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

    So in the LinkedHashMap case I interpret this as saying the iterator will return an ordered Set. It's true the LinkedHashMap API is not explicit about this but you could just try it out and observe your output.