View Javadoc
1 /*** 2 * GroupByOperator.java 3 * 4 * $Author: mballesteros $ 5 * $Date: 2003/11/28 19:18:03 $ 6 * $Revision: 1.1 $ 7 */ 8 package net.sf.jec.namedop; 9 10 import java.util.ArrayList; 11 import java.util.Collection; 12 import java.util.HashMap; 13 import java.util.Iterator; 14 import java.util.List; 15 import java.util.Map; 16 17 import net.sf.jec.EvaluationException; 18 19 /*** GroupByOperator returns a Map containing keyed groups of elements. If the 20 * context object is a collection, the collection will be divided into groups 21 * and keyed in the Map. If the context object is a Map, the operation will be 22 * recursive on each map entry, so it is possible to group a group. 23 * 24 * @author mballesteros 25 */ 26 public class GroupByOperator extends GroupOperator { 27 28 private boolean throwExceptions; 29 30 /*** Creates a new SumOperator 31 */ 32 public GroupByOperator() { } 33 34 /*** Returns a function representation String for this operator 35 */ 36 public String toFunctionString() { 37 return "Groupby(" + argOps[0] 38 + (nestedOp == null ? "" : ", " + nestedOp) + ")"; 39 } 40 41 /*** Returns an expression String representation for this operator 42 */ 43 public String toExpressionString() { 44 return (nestedOp == null ? "" : nestedOp.toString()) + ".groupby(" + argOps[0] + ")"; 45 } 46 47 48 /*** Returns the associated value to the given context and root context 49 * @param rootCtx The root context, needed for operators that require 50 * expression evaluation from root point. Example: Indexer operators 51 * @param ctx The current context where the operator will work over 52 */ 53 protected Object directMap(Object rootCtx, Object ctx) throws EvaluationException { 54 if (ctx instanceof Collection) { 55 return groupBy( rootCtx, (Collection) ctx ); 56 } else if (ctx instanceof Map) { 57 return applyToGroup(rootCtx, (Map) ctx ); 58 } else { 59 return null; 60 } 61 } 62 63 /*** Groups a collection... 64 */ 65 private Object groupBy(Object rootCtx, Collection c) throws EvaluationException { 66 Map out = new HashMap(); 67 List groupList; 68 Object key, obj; 69 Iterator it = c.iterator(); 70 while (it.hasNext()) { 71 obj = it.next(); 72 key = argOps[0].apply(rootCtx, obj); 73 groupList = (List) out.get(key); 74 if (groupList == null) { 75 groupList = new ArrayList(); 76 out.put(key, groupList); 77 } 78 groupList.add(obj); 79 } 80 return out; 81 } 82 83 }

This page was automatically generated by Maven