Java Lists: Group by element property (as Ruby group_by method)

This is a very funny function, similar to group_by from Ruby.
It takes a collection and it transforms to a hash, having keys the property *groupBy*, and values the objects having that property.

A usage example:

collectionToHash(users, "name"); // returns a hash where the keys are the distinct user names, and the values are lists of users having that property.

public static SortedMap<String, ArrayList<Object>> collectionToHash(Collection list, String groupBy){
 TreeMap<String, ArrayList<Object>> hash = new TreeMap<String, ArrayList<Object>>();

 for(Object obj : list){
   Class<?> klass = obj.getClass();
   String groupByGetter = groupBy;

   try {
   // dynamic method invocation
     Method m = klass.getMethod(groupByGetter);
     Object result = m.invoke(obj);
     String resultAsKey = result.toString();

     ArrayList<Object> arrayList;
       arrayList = hash.get(resultAsKey);
       arrayList = new ArrayList<Object>();
       hash.put(resultAsKey, arrayList);

 }catch (SecurityException e) {
 } catch (NoSuchMethodException e) {



 return hash;

One Response

  1. Very nice method! Thanks!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: