是否有我缺少的模式或内置函数,或者我应该像这样循环
public List<MyObject> convert(List<String> myStrings){
List<MyObject> myObjects = new ArrayList<MyObject>(myStrings.size());
Integer i = 0;
for(String string : myStrings){
MyObject myObject = new myObject(i, string);
myObjects.add(object);
i++;
}
return myObjects;
}
这是因为我需要将列表保存到数据库并保留顺序。
最佳答案
您可以使用 Guava :
List<MyObject> myObjects = Lists.transform(myStrings,
new Function<String, MyObject>() {
private int i = 0;
public MyObject apply(String stringValue) {
return new MyObject(i++, stringValue);
}
});
不过,实际上它只是将迭代带入库中。就实际编写的代码而言,在 Java 8 引入闭包之前,情况大致相同。
但是,您应该知道像这样(使用 i
)使函数有状态是错误的形式,因为现在它应用于列表的顺序很重要。
关于java - 将 List<String> 转换为 List<MyObject>,其中 MyObject 包含一个表示顺序的 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7448159/