On Apr 21, 3:08 am, Daniel Pitts
<newsgroup.spamfil...@virtualinfinity.net> wrote:
lstephen wrote:
Hi,
I'm looking at the signature for something like a 'map' function.
For List it may be something like:
List<B> map(List<A> a, UnaryFunction<A, B> f)
But, I want I'd rather it not be List specific, so I was after
something like:
T<B> map(T<A> a UnaryFunction<A, B> f)
But, the compiler doesn't like this ;)
Any ideas on how or whether this is possible?
Thanks,
Levi
How about this:
public static <A, B, T extends Collection<B>> T map(Iterable<A> source,
T dest, UnaryFunction<A, B> f) {
for (A a: source) {
dest.add(f.call(a));
}
return dest;
}
Example usage:
Set<Foo> foos = map(inputCollection, new HashSet<Foo>(), myFunction);
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>
I agree that this covers the common case. But, I was looking for a way
to improve this in two ways.
1. the 'map' concept can be applied to other, non-collection, types
(e.g., Haskell's Maybe type)
2. I wanted to express the restriction that the type passed in was
what came back (e.g., If a Set was passed in, a Set would be returned)
Note that there would be more than one implementation of map around,
so the general type would only appear in the interface.
Thanks,
Levi
allows the caller to specify the type-out. Maybe you want to convert a
List to a Set while applying this mapping, or visa versa.