简体   繁体   English

从HashMap检索密钥

[英]Retrieve key from HashMap

How to retrieve index of a map using key value? 如何使用键值检索地图索引?

I have a map with string as key and int as value. 我有一个地图,其中字符串作为键,而int作为值。 I will pass map and key value to a method,in that method based on the index of the passed key value it will return either true or false. 我将映射和键值传递给一个方法,在该方法中,根据所传递键值的索引,它将返回true或false。 I need this util method for my application. 我的应用程序需要此util方法。

package sample;

import java.util.HashMap;
import java.util.Map;

public class MAp {
    public static void main(String args[]) {
        Map<String, Integer> sampleMap = new HashMap<String, Integer>();
        sampleMap.put("ABC", 12);
        sampleMap.put("DEF", 13);
        boolean flag = canAllocate("ABC", sampleMap);
    }

    private static boolean canAllocate(String string, Map<String, Integer> sampleMap) {
        if (sampleMap.containsKey("ABC")) {
            int index = 0;
            // I need to get index of "ABC" in map;
            if (index == 0) {
                return true;
            }
        }
        return false;
    }
}

I would suggest you try using a LinkedHashMap , which will preserve the order, then do as Mena suggested. 我建议您尝试使用LinkedHashMap ,它将保留顺序,然后按照Mena的建议进行操作。 Otherwise, the 'order' doesn't mean much. 否则,“订单”意义不大。

You could just iterate the keySet and increment an int . 您可以只迭代keySet并增加一个int

index i = 0;
for (String key: sampleMap.keySet()) {
    if (key.equals(myString)) {
        return i;
    }
    else {
        i++;
    }
}
return -1;

To be noted, there is no indexing as such in the key set, so the whole functionality seems to have little value. 要注意的是,密钥集中没有这样的索引,因此整个功能似乎没有什么价值。

" // I need to get index of "ABC" in map " “ //我需要获取地图中“ ABC”的索引”

It has no sense to do that, "ABC" itself is a sort of index ine the MAP. 这样做是没有意义的,“ ABC”本身是MAP中的一种索引。 Key -> Map 键->地图

Index -> Array/List 索引->数组/列表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM