Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordered List Map implementation in Java

Tags:

java

list

map

I was wondering if there is a class out there that implements both the Map and List interfaces in Java.

I have a data structure that is primarily a Map. I map strings (IDs) to Images. But in a specific part of my code, I need to present the user with all the available IDed Images. The only way to do that so far is to write this:

for (String id : myMap.keySet()) {
    // get the image like this "myMap.get(id)" 
}

So it would be nice to have a class that implements both Map and List so I could simply write:

for (Image img : myMap) {
  // the image is img
}

Does anyone know of such an implementation?

EDIT: After viewing the answers (which are all correct, voted up), I now realize I would also need the map to be sorted. When I say "sorted", all I mean is that I would like it to have the values in a specific order, one that I would be able to modify. I know this is not the original question, but I just realized that I need that.

EDIT 2: It seems I am indecisive. What I need is an ordered map, not a sorted one. Sorry for the confusion, people.

like image 871
Savvas Dalkitsis Avatar asked Jul 31 '09 12:07

Savvas Dalkitsis


People also ask

Is Map an ordered collection in Java?

The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet , keySet and values methods).

How is Map implemented in Java?

You can implement maps in Java from two interfaces: Map and SortedMap. The SortedMap interface extends the Map interface. There are three classes to implement maps. These three classes are HashMap, LinkedHashMap, and TreeMap.

Is there an ordered HashMap?

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

If you need your items in a specific order, LinkedHashMap is your friend - it keeps items in insertion order. TreeMap will keep your items in an order defined by either a Comparator you give or a compareTo method of the key.

like image 158
Tadeusz Kopec for Ukraine Avatar answered Oct 14 '22 09:10

Tadeusz Kopec for Ukraine