0 votes
1 view
in Java by (4.1k 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 (46.1k 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.

Related questions

0 votes
1 answer
asked Aug 26, 2019 in Java by Krishna (2.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !