开发者

Finding an Object in a List

I have a List in a SelectOneMenu. When the user selects one of this list, it gives me the value, not the label of it. The thing I need is that label to display it on the screen. Is there a easier way to do it?

The way i'm doing right now is with a foreach li开发者_C百科ke this:

for(SelectItem si : listOfSomething) {
 if (si.getValue().equals(myValue) {
  theLabelIs = si.getLabel();
  break;
 }
}

Maybe I didn't explain it well, so please tell me and I'll try to explain better.


Use a Map instead where item values are the map key and item labels are the map value.

private Map<String, String> options;

public Bean() {
    options = new HashMap<String, String>();
    options.put("value1", "label1");
    options.put("value2", "label2");
    options.put("value3", "label3");
    // ...
}

Then you can get it in the backing bean as follows:

String label = options.get(selectedValue);
// ...

or even in the view as follows

You have selected <h:outputText value="#{bean.options[bean.selectedValue]}" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜