I'm looking to set the key value pairing of a HashMap using JSTL only. Is this possible?
I know how to retrieve the key value pairs, but I haven't found a way to set them.
Any help would be appreciated.
Example of retrieving HashMap key/value pairs using JSTL:
<c:forEach var="hash" items="${myHashMap}">
<c:out value="${hash.key}" />
<c:out value="${hash.value}" />
...
1. Add values to a Map. The standard solution to add values to a map is using the put() method, which associates the specified value with the specified key in the map. Note that if the map already contains a mapping corresponding to the specified key, the old value will be replaced by the specified value.
put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole.
a) The values can be stored in a map by forming a key-value pair. The value can be retrieved using the key by passing it to the correct method. b) If no element exists in the Map, it will throw a 'NoSuchElementException'. c) HashMap stores only object references.
You can use the same technique to loop over a HashMap in JSP which we have used earlier to loop over a list in JSP. The JSTL foreach tag has special support for looping over Map, it provides you both key and value by using var attribute. In the case of HashMap, object exported using var contains Map. Entry object.
You can use the <c:set>
.
<c:set target="${myHashMap}" property="key" value="value"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With