JSF how to iterate over map using ui:repeat
2011/07/07 § 3 Comments
private Map<String, ArrayList<Person>> myMap = new TreeMap<String, ArrayList<Person>>();
This is how my map look like and i want to display both key and value pair on my html page. ui:repeat doesn’t handle the Sets or Maps by default so here is the work around how we can make it work.
Reguar getter seter Person Class
public class Person {
private String name = "";
private String gender = "";
private String address = "";
public Person(String name, String gender, String address) {
this.name = name;
this.gender = gender;
this.address = address;
}
..
..
}
Make a function that returns only the keys of map
private ArrayList<String> keys = new ArrayList<String>();
private void myKeys(){
for(String key: blocks.keySet()){
keys.add(key);
}
}
Call the Map on jsf page as follows,
<ui:repeat value="#{mapBean.keys}" var="key">
<ice:outputLabel value="#{key}"/>
<ui:repeat var="item" value="#{mapBean.myMap[key]}">
<ice:outputLabel value="#{item.name}"/>
<ice:outputLabel value="#{item.adress}"/>
</ui:repeat>
</ui:repeat>
Perfect trick, helped my a lot.
You can use Map.keySet() too
Map.keySet() doesn’t work. Since iteration over sets are not supported. So only the above solution with List of keys work. Thanks the tip!!