Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EL get value of a HashMap by Integer key

Tags:

jsp

jstl

el

I have this HashMap:

    Map<Integer, String> odometerMap = new LinkedHashMap<Integer, String>();
    odometerMap.put(0, getLocaleForKey("drop-down.any"));
    odometerMap.put(1, "< 1000");
    odometerMap.put(2, "1000 - 5000");
    odometerMap.put(3, "5000 - 10000");
    odometerMap.put(4, "10000 - 20000");
    odometerMap.put(5, "20000 - 30000");
    odometerMap.put(6, "30000 - 40000");
    odometerMap.put(7, "40000 - 60000");
    odometerMap.put(8, "60000 - 80000");
    odometerMap.put(9, "> 80000");

My goal in JSP is to print for example ${odometerMap[2]} (result is empty string):

    <c:out value="${odometerMap[2]}"/>

If I print only ${odometerMap} I get the full map:

{0=Any, 1=< 1000, 2=1000 - 5000, 3=5000 - 10000, 4=10000 - 20000, 5=20000 - 30000, 6=30000 - 40000, 7=40000 - 60000, 8=60000 - 80000, 9=> 80000}

How can I print only an element of my choice? Ex: 2?

Thank you

like image 990
Mircea Stanciu Avatar asked Sep 03 '12 12:09

Mircea Stanciu


People also ask

Can we use integer as key in HashMap?

It can store different types: Integer keys and String values or same types: Integer keys and Integer values. HashMap is similar to HashTable, but it is unsynchronized. It is allowed to store null keys as well, but there can only be one null key and there can be any number of null values.

Can we use primitives as key in HashMap?

The keys and values of a map can be any reference type. We can't use primitive types because of a restriction around the way generics were designed. A HashMap allows one null key and multiple null values. It doesn't preserve the order of the elements and doesn't guarantee the order will remain the same over time.

How does HashMap increase value by 1?

Increase the value of a key in HashMap 2.1 We can update or increase the value of a key with the below get() + 1 method. 2.2 However, the above method will throw a NullPointerException if the key doesn't exist. The fixed is uses the containsKey() to ensure the key exists before update the key's value.


2 Answers

In EL, numbers are treated as Long. It's looking for a Long key. It'll work if you use Long instead of Integer as map key.

Map<Long, String> odometerMap = new LinkedHashMap<Long, String>();
odometerMap.put(0L, getLocaleForKey("drop-down.any"));
odometerMap.put(1L, "< 1000");
// ...
like image 172
BalusC Avatar answered Sep 20 '22 10:09

BalusC


An alternative could be using a String as the key

Map<String, String> odometerMap;

.. and:

<c:out value="${odometerMap['2']}"/>

But, it's better to use a List of Strings since your key doesn't have any clear meaning:

List<String> odometers = new ArrayList<String>();
odometers.add(getLocaleForKey("drop-down.any"));
// etc

.. and:

<c:out value="${odometers[2]}"/>
like image 32
Jasper de Vries Avatar answered Sep 17 '22 10:09

Jasper de Vries