Overridden map functions in the Collections classes
Pete Guyatt
pete at guyatt.ca
Wed Oct 3 17:42:44 PDT 2012
Hi All,
Hopefully this isn't too much of a stupid suggestion but I would like to
provide overridden implementations of the map functions to return the same
interface depending on the type of Collections interface we are using.
The reason for this is I am trying to retrofit an application I use to
support lambdas. This was the first stumbling block I came across since I
use a very similar pattern to what the map function provides in the
original codebase of this application. However depending on what type of
Collection I needed -- List, Set or Collection -- I would call different
methods to return the type I needed, for example:
return CollectionAdapter.unmodifiableCollection(query.getResultList(), new
Transformer<Object, String>() {
@Override
public String transform(Object value) {
return value.toString();
}
});
Just to try and back this suggestion up a little I can see a couple of
good reasons for doing such as:
It will help provide an interface between using the map function and
legacy API's
The List implementation Maps well to using models for UI's etc or for the
Collection example it works for when I need to call size (we could call
the count() function I guess!)
I would really appreciate some feedback on this suggestion, and I hope
it's a reasonable ask or maybe I just don't know any better!
Thanks,
Pete
-- code suggestions below
public interface Collection<E> extends Iterable<E>, Fillable<E> {
Other methods
@Override
<U> Collection<U> map(Mapper<? super T, ? extends U> mapper) default {
return CollectionsHelper.map(this, mapper);
}
}
public interface List<E> extends Collection<E> {
@Override
<U> List<U> map(Mapper<? super T, ? extends U> mapper) default {
return CollectionsHelper.map(this, mapper);
}
}
Also the same thing for Set etc with the CollectionHelper being defined
such as:
public class CollectionHelper {
private CollectionHelper() {}
public static <T, R> Collection<R> map(Collection<? extends T>
collection, Mapper<? super T, ? extends R> mapper) {
final Collection<R> view = new AbstractCollection<R>() {
@Override
public Iterator<R> iterator() {
return collection.map(mapper).iterator();
}
@Override
public int size() {
return collection.size();
}
};
return Collections.unmodifiableCollection(view);
}
public static <T, R> List<R> map(List<? extends T> list, Mapper<?
super T, ? extends R> mapper) {
final List<R> view = new AbstractList<R>() {
@Override
public R get(int index) {
return mapper.map(list.get(index));
}
@Override
public int size() {
return list.size();
}
};
return Collections.unmodifiableList(view);
}
// Set and other code etc
}
More information about the lambda-dev
mailing list