Is it possible to get element from HashMap by its position?

后端 未结 14 1440
时光说笑
时光说笑 2020-12-12 18:31

How to retrieve an element from HashMap by its position, is it possible at all?

14条回答
  •  隐瞒了意图╮
    2020-12-12 19:14

    By default, java LinkedHasMap does not support for getting value by position. So I suggest go with customized IndexedLinkedHashMap

    public class IndexedLinkedHashMap extends LinkedHashMap {
    
        private ArrayList keysList = new ArrayList<>();
    
        public void add(K key, V val) {
            super.put(key, val);
            keysList.add(key);
        }
    
        public void update(K key, V val) {
            super.put(key, val);
        }
    
        public void removeItemByKey(K key) {
            super.remove(key);
            keysList.remove(key);
        }
    
        public void removeItemByIndex(int index) {
            super.remove(keysList.get(index));
            keysList.remove(index);
        }
    
        public V getItemByIndex(int i) {
            return (V) super.get(keysList.get(i));
        }
    
        public int getIndexByKey(K key) {
            return keysList.indexOf(key);
        }
    }
    

    Then you can use this customized LinkedHasMap as

    IndexedLinkedHashMap indexedLinkedHashMap=new IndexedLinkedHashMap<>();
    

    TO add Values

    indexedLinkedHashMap.add("key1",UserModel);
    

    To getValue by index

    indexedLinkedHashMap.getItemByIndex(position);
    

提交回复
热议问题