Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Ordered Map

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); } 
like image 939
Whatsit Avatar asked Mar 19 '09 18:03

Whatsit


People also ask

What is an ordered map in Java?

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.

Is map an ordered collection in Java?

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.

What is an ordered map?

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.

Is HashMap an ordered map?

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.


1 Answers

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 order
  • values() which returns a collection of all values in the ascending order of the corresponding keys

So 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.

like image 126
dmeister Avatar answered Oct 25 '22 22:10

dmeister