Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (2.6k 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 (46k 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
0 votes
1 answer
asked Oct 27, 2019 in Java by Shubham (3.9k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...