Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 myObjects;
}

Its because I need to persist the list to a database and retain the ordering.

like image 961
NimChimpsky Avatar asked Sep 16 '11 17:09

NimChimpsky


2 Answers

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.

like image 107
Mark Peters Avatar answered Nov 07 '22 06:11

Mark Peters


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.

like image 25
Hyangelo Avatar answered Nov 07 '22 04:11

Hyangelo