Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display key and value of HashMap entries in JSF page

Tags:

hashmap

jsf

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>?

like image 373
Sweety Avatar asked Jun 03 '11 10:06

Sweety


People also ask

How to print the value of a key in the map?

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.

How to print key value in HashMap 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.

Can we get key from value in HashMap?

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().


2 Answers

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.

like image 123
jmj Avatar answered Sep 21 '22 03:09

jmj


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

like image 34
Snozzlebert Avatar answered Sep 21 '22 03:09

Snozzlebert