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
Convert ArrayList < String> to ArrayList<SelectItem>
提问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 SelectItem
object(s) anymore. Just a plain vanilla String
or 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 Foo
has properties id
and name
.
或者,一组 Javabeans,假设Foo
具有属性id
和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:
也可以看看:
回答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 SelectItem
is, so I will suppose you have a method for converting a String
to 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
Collection<SelectItem> result = Collections2.transform(
listout,
new Function<String, SelectItem>(){
@Override
public SelectItem apply(String s) {
return createSelectItem(s);
}
});