Is there a pattern, or built in function I am missing or shall I just loop through like so
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;
}
Its because I need to persist the list to a database and retain the ordering.
You can use 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);
}
});
Really it just brings the iteration into the library though. In terms of actual code written, it will be about the same until closures are introduced with Java 8.
However, you should know that making the function stateful like this (with i
) is bad form since now the order in which it's applied to the list is important.
Closures and lambdas that are coming in Java 8 should allow Java to have things like Mapper and Reducer functions(as in MapReduce). In fact, if you are following the latest developments from Project Lambda you would see lots of sample lambda code operating on collections.
e.g.
Collections.sort(people,
#{ Person x, Person y -> x.getLastName().compareTo(y.getLastName()) });
But until then the code you posted in your question should suffice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With