You are here: start » Snippets » Quickhacks

Quickhacks

map for Java 5.0

I needed a quick but dynamic way to call a method of each object in a list, and return a list of the return values of those calls. The following map function, resembling the built-in map from Python in combination with a lambda x: x.method() (pure coincedence, really! :-P), does this job.

/**
 * Returns a list of return values for calling the method on each item in the input
 * list.
 * 
 * @param method The method to call on each item of the list.
 * @param list The list of items to process.
 * 
 * @return A list of return values.
 * 
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 * @throws InvocationTargetException
 */
@SuppressWarnings("unchecked")
public static List map(Method method, List list) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
    List retList = new LinkedList();
    for (Object obj : list)
        retList.add(method.invoke(obj, new Object[]{}));
    return retList;
}

Usage example:

Method method = User.class.getMethod("getUsername", (Class[]) null);
List retList = ListUtils.map(method, userList); // retList now contains the usernames of the users in userList
snippets/quickhacks.txt · Last modified: 2008/11/16 23:44 by foosel