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;
if(hash.containsKey(resultAsKey)){
arrayList = hash.get(resultAsKey);
} else{
arrayList = new ArrayList<Object>();
hash.put(resultAsKey, arrayList);
}
arrayList.add(obj);
}catch (SecurityException e){
.....
}catch (NoSuchMethodException e){
....
}
return hash;
}
轉貼自http://vladzloteanu.wordpress.com/2009/05/20/java-lists-group-by-element-property-as-ruby-group_by-method/
沒有留言:
張貼留言