I'm writing an adapter framework where I need to convert a list of objects from one class to another. I can iterate through the source list to do this as in
Java: Best way of converting List<Integer> to List<String>
However, I'm wondering if there is a way to do this on the fly when the target list is being iterated, so I don't have to iterate through the list twice.
As an alternative to the iterator pattern, you can use a abstract generic mapper class, and only override the transform method:
the implementation:
This would be useful is you have to use transformations every time, encapsulating the process. So you can make a library of collection mappers very easy.
Java 8 way:
assuming
Wrapper
class has a constructor accepting aString
.Well, you could create your own iterator wrapper class to do this. But I doubt that you would save much by doing this.
Here's a simple example that wraps any iterator to a String iterator, using Object.toString() to do the mapping.
My answer to that question applies to your case:
The transformed list is a view on the original collection, so the transformation happens when the destination
List
is accessed.Lambdaj allows to do that in a very simple and readable way. For example, supposing you have a list of Integer and you want to convert them in the corresponding String representation you could write something like that;
Lambdaj applies the conversion function only while you're iterating on the result. There is also a more concise way to use the same feature. The next example works supposing that you have a list of persons with a name property and you want to convert that list in an iterator of person's names.
Pretty easy. Isn't it?
That question does not iterate through the list twice. It just iterates once and by far is the only known method.
Also you could use some transformer classes in commons-collections of google-collections but they all do the same thing under the hood :) the following being one way