I have a basic java use class object that extends WCMUSE and a simple hashmap method - in the sightly code - I have something like
${item}
${item.key}
${item.value}
does not work - how do I return key/value pair in sightly code
Generally, To get all keys and values from the map, you have to follow the sequence in the following order: Convert Hashmap to MapSet to get set of entries in Map with entryset () method.: use getKey () and getValue () methods of the Map.Entry to get keys and values.
If you want to get the set of keys from map, you can use keySet () method Set keys = map.keySet (); System.out.println ("All keys are: " + keys); // To get all key: value for (String key: keys) { System.out.println (key + ": " + map.get (key)); }
0 If you want to get key from value, its best to use bidimap (bi-directional maps) , you can get key from value in O(1) time. But, the drawback with this is you can only use unique keyset and valueset. There is a data structure called Table in java, which is nothing but map of maps like.
Last Updated : 26 Nov, 2018 The java.util.HashMap.get () method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.
There is an example at Sightly Intro Part 3 and the use of ${item} and ${itemList} as a variables is documented on the AEM Docs Sightly Page. This page also gives the following example for accessing dynamic values:
<dl data-sly-list.child="${myObj}">
<dt>key: ${child}</dt>
<dd>value: ${myObj[child]}</dd>
</dl>
Here is an example with a simple HashMap.
HTML with Sightly:
<div data-sly-use.myClass="com.test.WcmUseSample" data-sly-unwrap>
<ul data-sly-list.keyName="${myClass.getMyHashMap}">
<li>KEY: ${keyName}, VALUE: ${myClass.getMyHashMap[keyName]}</li>
</ul>
</div>
Java:
package com.test;
import java.util.HashMap;
import java.util.Map;
import com.adobe.cq.sightly.WCMUse;
public class WcmUseSample extends WCMUse {
private Map<String, String> myHashMap;
public void activate() throws Exception {
myHashMap = new HashMap<String, String>();
for (int i = 0; i < 10; ++i) {
myHashMap.put(""+i, "Hello "+i);
}
}
public Map<String,String> getMyHashMap() {
return myHashMap;
}
}
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