Method to extract all keys from LinkedHashMap into a List

前端 未结 2 620
攒了一身酷
攒了一身酷 2021-01-07 21:51

I am working with many LinkedHashMap that are either LinkedHashMap, LinkedHashMap or Linke

相关标签:
2条回答
  • 2021-01-07 22:04

    The ordering is important which is why I don't think I can use myMap.keySet() which is a Set

    The Map#keySet() method for LinkedHashMap will return the set in insertion order. Here's a quote from Map documentation:

    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, you don't need to write a separate method for that. Methods like keySet() and entrySet() will return the entries in the insertion order only.


    Well, if you really want a List<Keys>, then you can directly do:

    List<Long> keys = new ArrayList<>(target.keySet());
    

    .. wherever you want a List. You don't need the method at all.

    0 讨论(0)
  • 2021-01-07 22:22

    LinkedHashMap's consistent ordering applies to keys, values and entries.

    You should be just fine doing:

    ArrayList<Long> keys = new ArrayList<>(target.keySet());
    

    If you need more assurance, take a look at the source code for LinkedHashMap. The important part:

    private class KeyIterator extends LinkedHashIterator<K> {
        public K next() { return nextEntry().getKey(); }
    }
    
    private class ValueIterator extends LinkedHashIterator<V> {
        public V next() { return nextEntry().value; }
    }
    
    private class EntryIterator extends LinkedHashIterator<Map.Entry<K,V>> {
        public Map.Entry<K,V> next() { return nextEntry(); }
    }
    
    // These Overrides alter the behavior of superclass view iterator() methods
    Iterator<K> newKeyIterator()   { return new KeyIterator();   }
    Iterator<V> newValueIterator() { return new ValueIterator(); }
    Iterator<Map.Entry<K,V>> newEntryIterator() { return new EntryIterator(); }
    

    So the iterators for the keys, values and entries all come from the same source (nextEntry()) which uses the linked list for iteration order.

    0 讨论(0)
提交回复
热议问题