I would like to display HashMap
keys and its associated value in the JSF UI.
How can I achieve this? How can I iterate over a HashMap
in JSF page using some iterator component like <h:datatable>
?
Using toString() For displaying all keys or values present on the map, we can simply print the string representation of keySet() and values() , respectively. That's all about printing out all keys and values from a Map in Java.
Print HashMap Elements in Java This is the simplest way to print HashMap in Java. Just pass the reference of HashMap into the println() method, and it will print key-value pairs into the curly braces.
Get keys from value in HashMap To find all the keys that map to a certain value, we can loop the entrySet() and Objects. equals to compare the value and get the key. The common mistake is use the entry. getValue().
Only <c:forEach>
supports Map
. Each iteration gives a Map.Entry
instance back (like as in a normal Java for
loop).
<c:forEach items="#{yourBean.map}" var="entry">
<li>Key: #{entry.key}, value: #{entry.value}</li>
</c:forEach>
The <h:dataTable>
(and <ui:repeat>
) only supports List
(JSF 2.2 will come with Collection
support). You could copy all keys in a separate List
and then iterate over it instead and then use the iterated key to get the associated value using []
in EL.
private Map<String, String> map;
private List<String> keyList;
public void someMethodWhereMapIsCreated() {
map = createItSomeHow();
keyList = new ArrayList<String>(map.keySet());
}
public Map<String, String> getMap(){
return map;
}
public List<String> getKeyList(){
return keyList;
}
<h:dataTable value="#{yourBean.keyList}" var="key">
<h:column>
Key: #{key}
</h:column>
<h:column>
Value: #{yourBean.map[key]}
</h:column>
</h:dataTable>
Noted should be that a HashMap
is by nature unordered. If you would like to maintain insertion order, like as with List
, rather use LinkedHashMap
instead.
With <ui:repeat>
(JSF 2.2 and onwards):
<ui:repeat var="entry" value="#{map.entrySet().toArray()}">
key:#{entry.key}, Id: #{entry.value.id}
</ui:repeat>
Source: https://gist.github.com/zhangsida/9206849
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