6

Can I bind my h:dataTable/rich:dataTable with some Map? I found that h:dataTable can work only with List object and deleting in List can be very heavy.

udar_molota
  • 273
  • 6
  • 15
  • 1
    What makes you to think that it's less "heavy" when using a map? This is an absolute non-argument. – BalusC Jun 12 '12 at 13:15
  • because in map I have direct access to needed member and in list I need to go over all members for finding it. – udar_molota Jun 12 '12 at 15:37
  • What do you think that it's doing under the covers? How does a `Map` find the value associated with the key? Right, it's looping over all elements as well. The only difference is that this is hidden away by an extra method. Replacing `List` by `Map` makes it only unnecessarily more inefficient as with a `Map` you *basically* end up with a `Set` **and** a `List` instead of only a `List` which allows the fastest iteration possible when using the `ArrayList` implementation. – BalusC Jun 12 '12 at 15:38
  • 1
    Map uses Hash functions, that makes looping simple and quick. – udar_molota Jun 13 '12 at 08:39

2 Answers2

7

If you want to have only one method in your backing bean that provides the map, you can do something like this:

class Bean {
  public Map<T,U> getMap() {
    return yourMap;
  }
}

and use this in your JSF view

<h:dataTable value="#{bean.map.keySet().toArray()}" var="key"> 
   <h:outputText value="#{bean.map[key]}"/> 
</h:dataTable>

This converts the key set into an array, which can be iterated by the datatable. Using the "()"-expression requires Unified Expression Language 2 (Java EE 6).

tine2k
  • 1,521
  • 1
  • 16
  • 21
6

Yes, that's right. dataTable, ui:repeat and friends only work with Lists.

You can just add a managed bean method that puts map.keySet() or map.values() into a list depending on which you want to iterate over.

Typically when I want to iterate a map from a JSF view, I do something like

<h:dataTable value="#{bean.mapKeys}" var="key"> 
   <h:outputText value="#{bean.map[key]}"/> 
</h:dataTable>

with managed bean property

class Bean {
   public List<T> mapKeys() {
     return new ArrayList<T>(map.keySet());
   }
} 

or something like that.

Of course, this makes the most sense if you're using something like TreeMap or LinkedHashMap that preserves ordering.

wrschneider
  • 17,913
  • 16
  • 96
  • 176
  • 2
    The `` does currently **not** support iterating over `Set` nor `Collection`. This support will however be introduced in the upcoming JSF 2.2. So far only the `` supports maps. – BalusC Jun 12 '12 at 13:16