0 votes
1 view
in Java by (3.2k points)

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);

}

1 Answer

0 votes
by (26.5k points)

The SortedMap interface (with the implementation TreeMap) will help you.

The interface has the programs:

  • keySet() which delivers a set of the keys in rising order
  • values() which delivers a collection of all states in the ascending series of the similar keys

So this interface satisfies precisely your specifications. However, the keys necessity have a significant order. Otherwise, you can use the LinkedHashMap where the shipment is planned by the inclusion order.

...