开发者

Finding an Object in a List

开发者 https://www.devze.com 2023-03-08 02:38 出处:网络
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.

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

精彩评论

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