Display key and value of HashMap entries in JSF page

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

Tags:

Hashmap

Jsf