Basically, you create a functional interface:
public interface Func<In, Out> { public Out apply(In in); }
and then pass an anonymous subclass to your method.
Your method can either apply a function to each element in place:
public static <T> void applyToListInPlace(List<T> list, Func<T, T> f) { ListIterator<T> itr = list.listIterator(); while (itr.hasNext()) { T output = f.apply(itr.next()); itr.set(output); } }
or create a new List (basically creating a mapping from an input list to an output list):
public static <In, Out> List<Out> map(List<In> in, Func<In, Out> f) { List<Out> out = new ArrayList<Out>(in.size()); for (In inObj : in) { out.add(f.apply(inObj)); } return out; }
Which one is preferable depends on your use case. If your list is extremely large, an in-place solution may be the only viable; if you want to apply many different functions to the same source list, to make many lists of derivatives, you will need the map version.
Michael Myers May 22 '09 at 18:03 2009-05-22 18:03
source share