开发者

Convert a List<String> to a List<MyObject>, where MyObject contains an int representing the order

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 开发者_StackOverflow中文版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.


Your code will work fine. It's a little bit cleaner if you are using groovy because you could just do something like:

def i = 0;
def myObjects = myStrings.collect {str -> new MyObject(i++, str);}

Or Guava like Mark Peter's code. But, if you don't want to switch languages or import a new library, your code is perfectly fine.


I'll echo glowcoder's comment above and wonder why you need to transform the List -- which by definition has ordering information -- instead of simply persisting data to the database directly.

That said, I'll still offer a concise code snippet:

for (final String string : myStrings) {
    myObjects.add(new MyObject(myObjects.size(), string));
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜