GeoTools : Filter data store based on geometries in another

This little snippet shows an example of using the content of one DataStore to filter a second. As DataStores don't support this nativly it has to be done as a two step process.

 public FeatureCollection relate(DataStore a, DataStore b, Filter filter, short type) throws Exception{
        FeatureCollection source = a.getFeatureSource(a.getTypeNames()[0]).getFeatures(filter);
        FeatureIterator list = source.features();    
        FeatureCollection result = FeatureCollections.newCollection();
        FilterFactory fac = FilterFactory.createFilterFactory();
        short logic;
         switch(type){
            case AbstractFilter.GEOMETRY_DISJOINT:
            case AbstractFilter.GEOMETRY_BEYOND:
                    logic = LogicFilter.LOGIC_AND;
                    break;
            default:
                    logic = LogicFilter.LOGIC_OR;
        }
        LogicFilter geometryStack = fac.createLogicFilter(logic);

        while(list.hasNext()){
            Feature f = list.next();
            Geometry geom = f.getDefaultGeometry();
            GeometryFilter fi=fac.createGeometryFilter(type);
            fi.addLeftGeometry(fac.createLiteralExpression(geom));
            geometryStack.addFilter(fi);
        }
        result = b.getFeatureSource(b.getTypeNames()[0]).getFeatures(new DefaultQuery(null, geometryStack));
        return result;
        
    }