McMill
McMill

Reputation: 21

How to make linked hash map navigable?

I have a LinkedHashMap with the UUID keys and instance of my custom class as the value. Order of these entries must be the same as the inserting order. I need to process entries, and during processing I want to know, is I process the last entry, or not, and I want to move to previous or next entity. Looks like I need a hybrid between NavigableMap (navigation function) and LinkedHashMap (save inserting order).

How can I resolve this, what is the best way? If the LinkedHashMap elements are linked, why can't I move beetwen it?

Upvotes: 2

Views: 502

Answers (1)

Manos Nikolaidis
Manos Nikolaidis

Reputation: 22234

ListOrderedMap from Apache commons offers the functionality you describe. E.g.

ListOrderedMap<String, String> data = new ListOrderedMap<>();
data.put("2", "b");
data.put("1", "a");
data.put("5", "c");
System.out.println(data.firstKey());
System.out.println(data.lastKey());
System.out.println(data.get(1));
System.out.println(data.get("2"));

Note that there are get methods by int (insertion order) and by key and both are O(1) as it's backed by a HashMap and an ArrayList

Upvotes: 1

Related Questions