开发者

Convert ArrayList < String> to ArrayList<SelectItem>

I have an ArrayList<String> named listout, I want to convert it to an ArrayLis开发者_如何学Got<SelectItem>. How can I do that?

PS: JSF's selectItem


Based on your question history, you're using JSF 2. In this case, it's good to know that <f:selectItem> and <f:selectItems> do not require a single or a collection of SelectItem object(s) anymore. Just a plain vanilla String or even a Javabean is also perfectly fine.

So,

private String selectedItem;
private List<String> availableItems;

// ...

with

<h:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems value="#{bean.availableItems}" />
</h:selectOneMenu>

should work as good in JSF 2.

Or, a collection of Javabeans, assuming that Foo has properties id and name.

private Foo selectedItem;
private List<Foo> availableItems;

// ...

with

<h:selectOneMenu value="#{bean.selectedItem}">
    <f:selectItems value="#{bean.availableItems}" var="foo" itemValue="#{foo}" itemLabel="#{foo.name}" />
</h:selectOneMenu>

See also:

  • Our <selectOneMenu> wiki page


Assuming you mean JSF's SelectItem:

List<SelectItem> items = new ArrayList<SelectItem>(listout.size());
for(String value : listout){
    items.add(new SelectItem(value));
}
return items;


I don't know what SelectItem is, so I will suppose you have a method for converting a String to it, named createSelectItem().

You have to iterate through the strings and fill another ArrayList :

ArrayList<SelectItem> out = new ArrayList<SelectItem>();
for(String str : listout) {
    out.add(createSelectItem(str));


guava solution:

    Collection<SelectItem> result = Collections2.transform(
        listout, 
        new Function<String, SelectItem>(){
           @Override
           public SelectItem apply(String s) {
            return  createSelectItem(s);
    }
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜