Convert list <String> to list <MyObject>, where MyObject contains an int representing the order
Is there a template or inline function that I skip over, or am I just going through 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; }
This is because I need to save the list in the database and keep order.
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); } });
Indeed, this simply leads the iteration to the library. From the point of view of real code, it will be roughly the same until closure is introduced with Java 8.
However, you should know that making a stateful function like this one (with i
) is a bad form, since now the order in which it is applied to the list is important.
Closures and lambdas, which come in Java 8, should let Java have things like the Mapper and Reducer functions (like in MapReduce). In fact, if you follow the latest developments of Project Lambda, you will see many samples of lambda code that work with collections.
eg.
Collections.sort(people, #{ Person x, Person y -> x.getLastName().compareTo(y.getLastName()) });
But until then, the code you posted in your question should be sufficient.
Your code will work fine. This is a little cleaner if you use groovy because you can just do something like:
def i = 0; def myObjects = myStrings.collect {str -> new MyObject(i++, str);}
Or Guava, as Mark Peterβs code. But if you do not want to switch languages ββor import a new library, your code will be fine.
I exit the glowcoder comment above and wonder why you need to convert a List, which by definition has order information, rather than just directly transferring the data to the database.
However, I still suggest a short piece of code:
for (final String string : myStrings) { myObjects.add(new MyObject(myObjects.size(), string)); }