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

后端 未结 14 1421
时光说笑
时光说笑 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:12

    I'm assuming by 'position' you're referring to the order in which you've inserted the elements into the HashMap. In that case you want to be using a LinkedHashMap. The LinkedHashMap doesn't offer an accessor method however; you will need to write one like

    public Object getElementAt(LinkedHashMap map, int index) {
        for (Map.Entry entry : map.entrySet()) {
            if (index-- == 0) {
                return entry.value();
            }
        }
        return null;
    }
    

提交回复
热议问题