Object select = env.evaluate(selectExpression, context, false);
Object prevVar = context.getVariable(varName);
try {
Iterator<?> it = env.getCollectionIterator(select);
if(it == null) {
throw new EvaluationException("`" + selectExpression.toString() + "` should be array or collection (instead of "+select.getClass().getCanonicalName()+")");
}
if(instruction == SELECT || instruction == REJECT || instruction == COLLECT || instruction == COLLECTUNIQUE) {
Collection<Object> result = instruction == COLLECTUNIQUE ? new LinkedHashSet<Object>() : new ArrayList<Object>();
while(it.hasNext()) {
Object curr = it.next();
context.setVariable(varName, curr);
Object val = env.evaluate(foreachExpr, context, instruction == COLLECT || instruction == COLLECTUNIQUE);
if(instruction != COLLECT && instruction != COLLECTUNIQUE) {
boolean b = env.toBoolean(val) ^ (instruction == REJECT);
if(b) {
result.add(curr);
}
} else if(val instanceof Collection<?>) {
for(Object v : (Collection<?>) val) {
if(v!=null) {
result.add(v);
}
}
} else if(val instanceof Object[]) {
for(Object v : (Object[])val) {
if(v!=null) {
result.add(v);
}
}
} else if(val != null){
result.add(val);
}
}
return instruction == COLLECTUNIQUE ? new ArrayList<Object>(result) : result;
} else if(instruction == SORT) {
List<Object> result = new ArrayList<Object>();
final Map<Object, Comparable<Object>> sortKey = new HashMap<Object, Comparable<Object>>();
while(it.hasNext()) {
Object curr = it.next();
context.setVariable(varName, curr);
Object val = env.evaluate(foreachExpr, context, false);
if(!(val instanceof Comparable<?>)) {
throw new EvaluationException("`" + foreachExpr.toString() + "` should implement Comparable (instead of "+val.getClass().getCanonicalName()+")");
}
sortKey.put(curr, (Comparable<Object>)val);
result.add(curr);
}
Object[] arr = result.toArray();