getting a value from a map in java with index

时间:2015-06-15 14:56:54

标签: java collections

The item shown below is the result obtained from debugging a map

{0={PRODUCT_TYPE.PRODUCT_AMT=200}}

To store this value in a string I have used this code

String amountCheck=(String) productsFieldMap.get("PRODUCT_TYPE.PRODUCT_AMT");

However this does not seems to work. Can anyone suggest me a way to do this? The productsFieldMap represents the map where the values are stored.

3 个答案:

答案 0 :(得分:2)

Try this to find out what the map exactly contains:

for (Object key : productsFieldMap.keySet()) {
   System.out.println(key.toString() + ", " + productsFieldMap.get(key));
}

答案 1 :(得分:2)

I believe, you're looking for getting a key based on a value.

You cannot get the key based on a value, as get() accepts a key, not a value.

If you want to do so, you need to iterate over the HashMap and get the matching value and return the key of it.

public static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
    if (Objects.equals(value, entry.getValue())) {
        return entry.getKey();
    }
}
return null;
}

答案 2 :(得分:1)

I missed something here and with this I was able to get desired output.

Map result = (Map) productsFieldMap.get(0);
String amountCheck = (String) result.get("PRODUCT_TYPE.PRODUCT_AMT");