java 将 ArrayList <String> 转换为 ArrayList<SelectItem>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6744694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 17:06:56  来源:igfitidea点击:

Convert ArrayList < String> to ArrayList<SelectItem>

javajsf

提问by rym

I have an ArrayList<String>named listout, I want to convert it to an ArrayList<SelectItem>. How can I do that?

我有一个ArrayList<String>命名列表,我想将它转换为ArrayList<SelectItem>. 我怎样才能做到这一点?

PS: JSF's selectItem

PS:JSF的selectItem

回答by BalusC

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 SelectItemobject(s) anymore. Just a plain vanilla Stringor even a Javabean is also perfectly fine.

根据您的问题历史,您使用的是 JSF 2。在这种情况下,很高兴知道这一点<f:selectItem>并且<f:selectItems>不再需要单个或一组SelectItem对象。只是一个普通的香草String甚至一个 Javabean 也非常好。

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.

在 JSF 2 中应该也能正常工作。

Or, a collection of Javabeans, assuming that Foohas properties idand name.

或者,一组 Javabeans,假设Foo具有属性idname.

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:

也可以看看:

回答by Sean Patrick Floyd

Assuming you mean JSF's SelectItem:

假设你的意思是 JSF 的SelectItem

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

回答by slaphappy

I don't know what SelectItemis, so I will suppose you have a method for converting a Stringto it, named createSelectItem().

我不知道是什么SelectItem,所以我假设您有一种将 a 转换String为它的方法,名为 createSelectItem()。

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

您必须遍历字符串并填充另一个ArrayList

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

回答by u290629

guava solution:

番石榴解决方案

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