如何使用索引获取LinkedHashMap的值?

4

我是 Java 的新手... 我已经创建了一个类似于下面的链式哈希表:

Map<String, Double> MonthlyCPIMenu = new LinkedHashMap<String, Double>();
        MonthlyCPIMenu.put("1394/10", 0.0);
        MonthlyCPIMenu.put("1394/09", 231.6);
        MonthlyCPIMenu.put("1394/08", 228.7);
        MonthlyCPIMenu.put("1394/07", 227.0);
        MonthlyCPIMenu.put("1394/06", 225.7);

我知道如何使用以下方法找到每个项的索引(例如):

String duemonth="1394/08";
            int indexduemonth = new ArrayList<String>(MonthlyCPIMenu.keySet()).indexOf(duemonth);

但我不知道如何使用索引查找值。(我知道如何使用键获取值,但在这种情况下我应该使用索引)

3个回答

3
一种简单的方法是:
new ArrayList<String>(MonthlyCPIMenu.keySet()).get(index);

但是LinkedHashMap一般不支持高效的索引检索,并且它没有为此提供任何API。最好的算法就是使用MonthlyCPIMenu.keySet().iterator(),调用next()index次,然后返回最终next()的结果:

<K, V> K getKey(LinkedHashMap<K, V> map, int index) {
    Iterator<K> itr = map.keySet().iterator();
    for (int i = 0; i < index; i++) {
        itr.next();
    }
    return itr.next();
}

@mdehghani,这是给你的。 - Louis Wasserman

0

首先,您使用LinkedHashMap的特定原因是什么?一般来说,遍历键很便宜,查找为0(1)。为什么值的顺序很重要?

您可以使用get(key)方法从映射中检索值。

Map.get(key);

您可以使用以下方法来防止空值:

Map.get(key) != null ? Map.get(key) : "";

如果找到了键,它将返回该值,否则将返回一个空字符串。您可以用任何您想要的内容替换空字符串。


James B:原因是我正在使用与Spinner相关的Map,我需要用户选择的下一行,我认为唯一的方法是找到索引并获取(索引+1)的值。 - mdehghani
James B:你提供的方法似乎仅基于键检索值,并在我插入索引时返回null。 - mdehghani
正确,这就是如何从键值对中获取值。如果您想防止空值,则可以执行以下操作:Map.get(key) != null ? Map.get(key) : ""; - B... James B.
谢谢,但那不是我问题的答案。键和索引是不同的。 - mdehghani

0
如果你想获取值,那么请使用List接口并创建自己的类型。
public class MyValue {
String date;
String value;

public MyValue(String d, String v) {
    this.date = d;
    this.value = v;
}

public String getDate() {
    return date;
}

public String getValue() {
    return value;
}

}

然后使用List接口:

List<MyValue> list = new ArrayList<>();
// put all you values in the list
// get the values out by index in the list

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接