Iterator from specific object in LinkedHashMap

I have a LinkedHashMap, I have a key as an ID, what I am trying to achieve is the ability to search for an ID and, if present, has an iterator from that entry to the end of the map. What I have tried so far

Map<String, Obj> map = new LinkedHashMap<>();
Iterator it = map.entrySet().iterator();

      

But is there a way to make the iterator start at a specific object without doing a linear search and discovering it?

+3


source to share


2 answers


No, there is no such function in LinkedHashMap

.

But you can simulate it with List

just one work-around:

    Map<String, Object> map = new LinkedHashMap<>();
    Map<String, Integer> indexesMap = new HashMap<>(map.size());

    int index = 0;
    for (String key : map.keySet()) {
        indexesMap.put(key, index++);
    }

    List<Entry<String, Object>> entries = new ArrayList<>(map.entrySet());

    // ...

    String key = ...

    Iterator<Entry<String, Object>> iterator = entries.listIterator(indexesMap.get(key));

      

On each subsequent call, entries.listIterator

you get an O (1) iterator.



EDIT

If you also want the removal to be O (1), you shouldn't use LinkedHashMap

.

You can implement your own double linked list and store its nodes in HashMap

. Then search the node using the key from the map. When you get a node, you can move the rest of the subsequent entries from the linked list, or you can remove it in O (1) by removing it from both the map and the linked list.

+1


source


No, it is impossible for LinkedHashMap

. There tailMap

's an interface NavigableMap

that can help you do this ( map.tailMap(key).iterator()

), but that interface is not implemented LinkedHashMap

If TreeMap

(perhaps with a custom comparator) is a suitable replacement in your case, consider using it.



0


source







All Articles