Java中的有序列表映射实现 [英] Ordered List Map implementation in Java
问题描述
Map
和 List
接口。 我有一个数据结构,主要是一个 Map
。我将字符串(ID)映射到图像
s。但是在我的代码的特定部分,我需要向用户显示所有可用的ID $
for(String id:myMap.keySet()){
//获取像这样的图像myMap.get(id)
}
所以有一个类可以实现 Map
和 List
,所以我可以简单地写: / p>
for(Image img:myMap){
//图像是img
}
有没有人知道这样的实现?
EDIT :在查看答案(这些都是正确的,投了赞成票)后,我现在意识到我也需要将地图排序。当我说排序时,我的意思是,我希望它具有特定顺序的值,我可以修改。我知道这不是原来的问题,但我只是意识到我需要这个。
编辑2 :似乎我犹豫不决。我需要的是一个有序的地图,而不是一个排序的地图。
如果您按照特定顺序需要您的项目, LinkedHashMap 是您的朋友 - 它保留项目的插入顺序。 TreeMap将保持您的项目按照您给出的比较器或键的compareTo方法定义的顺序。
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 Image
s. 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.
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.
这篇关于Java中的有序列表映射实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!