Alex Rivera | Logout

Python-like list comprehension in Java

Asked 2009-05-22T17:57:13.857
72

Since Java doesn't allow passing methods as parameters, what trick do you use to implement Python like list comprehension in Java ?

I have a list (ArrayList) of Strings. I need to transform each element by using a function so that I get another list. I have several functions which take a String as input and return another String as output. How do I make a generic method which can be given the list and the function as parameters so that I can get a list back with each element processed. It is not possible in the literal sense, but what trick should I use ?

The other option is to write a new function for each smaller String-processing function which simply loops over the entire list, which is kinda not so cool.

Edit
Report

1 Answer

5

Apache Commons CollectionsUtil.transform(Collection, Transformer) is another option.

answered 2009-05-22T18:54:46.150

Your Answer