In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order?
So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap:
OrderedMap<Integer, String> om = new OrderedMap<>(); om.put(0, "Zero"); om.put(7, "Seven"); String o = om.get(7); // o is "Seven" List<Integer> keys = om.getKeys(); List<String> values = om.getValues(); for(int i = 0; i < keys.size(); i++) { Integer key = keys.get(i); String value = values.get(i); Assert(om.get(key) == value); }
SortedMap is an interface in the collection framework. This interface extends the Map interface and provides a total ordering of its elements (elements can be traversed in sorted order of keys). The class that implements this interface is TreeMap.
The Navigable map is usually sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time. There are three most useful implementations of it: TreeMap, ImmutableSortedMap, and ConcurrentSkipListMap.
An ordered map (also called a linked hash map in Java) is a data structure that allows amortized O(1) for access and mutation just like a map, but the elements maintain their order.
A HashMap contains values based on the key. It contains only unique elements. It may have one null key and multiple null values. It maintains no order.
The SortedMap interface (with the implementation TreeMap) should be your friend.
The interface has the methods:
keySet()
which returns a set of the keys in ascending ordervalues()
which returns a collection of all values in the ascending order of the corresponding keysSo this interface fulfills exactly your requirements. However, the keys must have a meaningful order. Otherwise you can used the LinkedHashMap where the order is determined by the insertion order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With