Example usage for com.google.common.collect Sets filter

List of usage examples for com.google.common.collect Sets filter

Introduction

In this page you can find the example usage for com.google.common.collect Sets filter.

Prototype

@GwtIncompatible("NavigableSet")
@SuppressWarnings("unchecked")
@CheckReturnValue
public static <E> NavigableSet<E> filter(NavigableSet<E> unfiltered, Predicate<? super E> predicate) 

Source Link

Document

Returns the elements of a NavigableSet , unfiltered , that satisfy a predicate.

Usage

From source file:org.opendaylight.controller.md.statistics.manager.FlowCapableTracker.java

@Override
public synchronized void onDataChanged(final DataChangeEvent<InstanceIdentifier<?>, DataObject> change) {
    logger.debug("Tracker at root {} processing notification", root);

    /*/*  w  w w . jav a 2  s . com*/
     * First process all the identifiers which were removed, trying to figure out
     * whether they constitute removal of FlowCapableNode.
     */
    final Collection<NodeKey> removedNodes = Collections2
            .filter(Collections2.transform(Sets.filter(change.getRemovedOperationalData(), filterIdentifiers),
                    new Function<InstanceIdentifier<?>, NodeKey>() {
                        @Override
                        public NodeKey apply(final InstanceIdentifier<?> input) {
                            final NodeKey key = input.firstKeyOf(Node.class, NodeKey.class);
                            if (key == null) {
                                // FIXME: do we have a backup plan?
                                logger.info("Failed to extract node key from {}", input);
                            }
                            return key;
                        }
                    }), Predicates.notNull());
    stats.stopNodeHandlers(removedNodes);

    final Collection<NodeKey> addedNodes = Collections2.filter(
            Collections2.transform(Sets.filter(change.getCreatedOperationalData().keySet(), filterIdentifiers),
                    new Function<InstanceIdentifier<?>, NodeKey>() {
                        @Override
                        public NodeKey apply(final InstanceIdentifier<?> input) {
                            final NodeKey key = input.firstKeyOf(Node.class, NodeKey.class);
                            if (key == null) {
                                // FIXME: do we have a backup plan?
                                logger.info("Failed to extract node key from {}", input);
                            }
                            return key;
                        }
                    }),
            Predicates.notNull());
    stats.startNodeHandlers(addedNodes);

    logger.debug("Tracker at root {} finished processing notification", root);
}

From source file:com.cloudera.gertrude.space.LayerImpl.java

@Override
public void assign(final ExperimentState state, List<DiversionCriterion> diversionCriteria,
        Map<String, FlagValueCalculator<Object>> overrides, Set<Integer> newExperimentIds) {
    if (!Sets.intersection(segmentIds, state.getExperimentIds()).isEmpty()) {
        // Diversion has already happened in this layer.
        return;/*from w  w  w  .  j a v  a2  s. c o m*/
    }

    for (DiversionCriterion criteria : diversionCriteria) {
        int bucket = -1;
        if (criteria.isRandom()) {
            bucket = random.nextInt(criteria.getNumBuckets());
        } else {
            Optional<String> identifier = state.getDiversionIdentifier(criteria.getId());
            if (identifier.isPresent()) {
                bucket = computeBucket(identifier.get(), criteria.getNumBuckets());
            }
        }
        if (bucket != -1) {
            Set<Segment> selected = findSegments(segmentsByDiversionBuckets.get(criteria.getId()), bucket,
                    state.getRequestTimeMsec());
            if (!selected.isEmpty()) {
                Set<Segment> valid = Sets.filter(selected, new Predicate<Segment>() {
                    @Override
                    public boolean apply(Segment segment) {
                        return segment.isValidFor(state);
                    }
                });
                if (valid.isEmpty()) {
                    // There were experiments for this bucket, but this request did not match any of them.
                    // Mark the request with the appropriate bias identifier.
                    newExperimentIds
                            .add(criteria.isRandom() ? info.getRandomBiasedId() : info.getFixedBiasedId());
                } else if (valid.size() == 1) {
                    // Divert the request into this segment
                    Iterables.getOnlyElement(valid).handle(state, diversionCriteria, overrides,
                            newExperimentIds);
                } else {
                    // Bad news
                    throw new IllegalStateException(
                            String.format("Multiple valid segments assigned to bucket %d in layer %d: %s",
                                    bucket, info.getLayerId(), valid.toString()));
                }
                return;
            }
        }
    }

    // Only reach this point if there were no matching experiments in this layer for the current request.
    newExperimentIds.add(info.getUnbiasedId());
}

From source file:gov.nih.nci.caarray.domain.file.FileTypeRegistryImpl.java

/**
 * {@inheritDoc}/*from   ww w  .  ja v  a 2s.c  o  m*/
 */
@Override
public Set<FileType> getParseableArrayDesignTypes() {
    return Sets.filter(this.types, new Predicate<FileType>() {
        @Override
        public boolean apply(FileType ft) {
            return ft.isParseableArrayDesign();
        }
    });
}

From source file:org.icgc.dcc.portal.model.UnionAnalysisRequest.java

public List<UnionUnit> toUnionSets() {

    val setSize = lists.size();
    val subsets = Sets.powerSet(this.lists);

    /*/*from  ww w.  j a  v a 2  s.c o m*/
     * Used to remove the empty set and itself from the subsets.
     */
    val predicate = new Predicate<Collection<?>>() {

        @Override
        public boolean apply(Collection<?> s) {
            val size = s.size();
            return (size > 0) && (size < setSize);
        }
    };
    val filteredSubsets = Sets.filter(subsets, predicate);
    val resultSize = filteredSubsets.size();

    val result = new ArrayList<UnionUnit>(resultSize + 1);

    for (val subset : filteredSubsets) {
        val unionUnit = new UnionUnit(Sets.difference(this.lists, subset), subset);
        result.add(unionUnit);
    }
    result.add(UnionUnit.noExclusionInstance(this.lists));

    return result;
}

From source file:org.spka.cursus.test.AbstractSPKASeries.java

/**
 * Get all the pilots in a Scotland series
 *//*w  w w .  j  a va  2  s  .co m*/
public Set<Pilot> getSeriesResultsPilots(final Series series) throws Exception {
    return Sets.filter(series.getPilots(), new Predicate<Pilot>() {
        @Override
        public boolean apply(@Nonnull Pilot pilot) {
            return SERIES_COUNTRIES.contains(pilot.getCountry());
        }
    });
}

From source file:com.facebook.buck.android.relinker.RelinkerRule.java

private static String getVersionScript(Set<String> needed, Set<String> provided) {
    Set<String> keep = new ImmutableSet.Builder<String>().addAll(Sets.intersection(needed, provided))
            .addAll(Sets.filter(provided, s -> {
                if (s.contains("JNI_OnLoad")) {
                    return true;
                }/*from  ww  w .  j  a  v  a  2s . c o  m*/
                if (s.contains("Java_")) {
                    return true;
                }
                return false;
            })).build();
    String res = "{\n";
    if (!keep.isEmpty()) {
        res += "global:\n";
    }
    for (String s : keep) {
        res += "  " + s + ";\n";
    }
    res += "local: *;\n};\n";
    return res;
}

From source file:org.caleydo.core.util.color.AlexColorPalette.java

public static Set<AlexColorPalette> getSets(int size, EColorSchemeType type) {
    return Sets.filter(getSets(size), type.isOf());
}

From source file:org.brooth.jeta.apt.processors.ProxyProcessor.java

public boolean process(TypeSpec.Builder builder, RoundContext context) {
    ClassName masterClassName = ClassName.get(context.metacodeContext().masterElement());
    builder.addSuperinterface(ParameterizedTypeName.get(ClassName.get(ProxyMetacode.class), masterClassName));

    MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder("applyProxy").addAnnotation(Override.class)
            .addModifiers(Modifier.PUBLIC).returns(boolean.class).addParameter(masterClassName, "master")
            .addParameter(Object.class, "real", Modifier.FINAL);

    for (Element element : context.elements()) {
        String realFieldName = element.getSimpleName().toString();
        ClassName realClassName = ClassName.bestGuess(element.asType().toString());
        final Proxy annotation = element.getAnnotation(Proxy.class);
        String proxyClassNameStr = MetacodeUtils.extractClassName(new Runnable() {
            public void run() {
                annotation.value();/*  w  w  w . ja va 2  s. c o  m*/
            }
        });
        TypeElement proxyTypeElement = processingContext.processingEnv().getElementUtils()
                .getTypeElement(proxyClassNameStr);
        ClassName proxyClassName = ClassName.bestGuess(proxyClassNameStr);

        TypeSpec.Builder proxyTypeSpecBuilder = TypeSpec.anonymousClassBuilder("")
                .addSuperinterface(proxyClassName)
                .addMethod(MethodSpec.methodBuilder("real").addAnnotation(Override.class)
                        .addModifiers(Modifier.PUBLIC).returns(realClassName)
                        .addStatement("return ($T) real", realClassName).build());

        TypeElement realTypeElement = (TypeElement) processingContext.processingEnv().getTypeUtils()
                .asElement(element.asType());
        Set<ExecutableElement> toImplementMethods = new HashSet<ExecutableElement>();
        for (Element subElement : ((TypeElement) realTypeElement).getEnclosedElements()) {
            if (subElement.getKind() == ElementKind.METHOD)
                toImplementMethods.add((ExecutableElement) subElement);
        }

        for (final Element subElement : ((TypeElement) proxyTypeElement).getEnclosedElements()) {
            if (subElement.getKind() == ElementKind.METHOD) {
                // todo: iterator.remove();
                toImplementMethods = Sets.filter(toImplementMethods, new Predicate<ExecutableElement>() {
                    public boolean apply(ExecutableElement input) {
                        return !input.toString().equals(subElement.toString());
                    }
                });
            }
        }

        for (ExecutableElement method : toImplementMethods) {
            TypeMirror[] params = new TypeMirror[method.getParameters().size()];
            String[] values = new String[params.length];
            int pi = 0;
            for (VariableElement param : method.getParameters()) {
                params[pi] = param.asType();
                values[pi] = param.getSimpleName().toString();
            }

            TypeMirror returnType = method.getReturnType();
            String methodNameStr = method.getSimpleName().toString();
            MethodSpec.Builder methodImplSpecBuilder = MethodSpec.methodBuilder(methodNameStr)
                    .addAnnotation(Override.class).addModifiers(Modifier.PUBLIC)
                    .returns(TypeName.get(returnType))
                    .addStatement((returnType.toString().equals("void") ? "" : "return ") + "real().$L($L)",
                            methodNameStr, Joiner.on(", ").join(values));

            for (int i = 0; i < params.length; i++)
                methodImplSpecBuilder.addParameter(TypeName.get(params[i]), values[i]);

            proxyTypeSpecBuilder.addMethod(methodImplSpecBuilder.build());
        }

        methodBuilder.beginControlFlow("if (real == master.$L)", realFieldName)
                .addStatement("master.$L = $L", realFieldName, proxyTypeSpecBuilder.build())
                .addStatement("return true").endControlFlow();
    }

    methodBuilder.addStatement("return false");
    builder.addMethod(methodBuilder.build());
    return false;
}

From source file:prm4j.indexing.model.JoinArgs.java

protected static List<Set<Parameter<?>>> getDisableSets(ParametricPropertyModel ppm, BaseEvent baseEvent,
        final Set<Parameter<?>> enableSet) {
    final Set<Parameter<?>> combination = Sets.union(baseEvent.getParameters(), enableSet);
    return toListOfParameterSetsAscending(
            Sets.filter(toParameterSets(ppm.getParametricProperty().getSpec().getBaseEvents()),
                    new Predicate<Set<Parameter<?>>>() {
                        @Override
                        public boolean apply(Set<Parameter<?>> baseEventParameterSet) {
                            return combination.containsAll(baseEventParameterSet)
                                    && !enableSet.containsAll(baseEventParameterSet);
                        }/*from   w  ww. j a va2 s.  c o  m*/
                    }));
}

From source file:com.eucalyptus.cloudwatch.domain.listmetrics.ListMetricManager.java

private static List<ListMetric> foldMetric(String accountId, String metricName, String namespace,
        Map<String, String> dimensionMap, MetricType metricType) {
    List<ListMetric> metrics = Lists.newArrayList();
    if (dimensionMap == null) {
        dimensionMap = new HashMap<String, String>();
    } else if (dimensionMap.size() > ListMetric.MAX_DIM_NUM) {
        throw new IllegalArgumentException("Too many dimensions for metric, " + dimensionMap.size());
    }//ww w  .j a  v a  2 s .c  om
    TreeSet<DimensionEntity> dimensions = new TreeSet<DimensionEntity>();
    for (Map.Entry<String, String> entry : dimensionMap.entrySet()) {
        DimensionEntity d = new DimensionEntity();
        d.setName(entry.getKey());
        d.setValue(entry.getValue());
        dimensions.add(d);
    }
    Set<Set<DimensionEntity>> permutations = null;
    if (metricType == MetricType.System) {
        // do dimension folding (i.e. insert 2^n metrics.  
        // All with the same metric name and namespace, but one for each subset of the dimension set passed in, including all, and none)
        if (!namespace.equals("AWS/EC2")) {
            permutations = Sets.powerSet(dimensions);
        } else {
            // Hack: no values in AWS/EC2 have more than one dimension, so fold, but only choose dimension subsets of size at most 1.
            // See EUCA-do dimension folding (i.e. insert 2^n metrics.  
            // All with the same metric name and namespace, but one for each subset of the dimension set passed in, including all, and none)
            permutations = Sets.filter(Sets.powerSet(dimensions), new Predicate<Set<DimensionEntity>>() {
                public boolean apply(@Nullable Set<DimensionEntity> candidate) {
                    return (candidate != null && candidate.size() < 2);
                }
            });
        }
    } else { // no folding on custom metrics
        permutations = Sets.newHashSet();
        permutations.add(dimensions);
    }
    for (Set<DimensionEntity> dimensionsPermutation : permutations) {
        ListMetric metric = new ListMetric();
        metric.setAccountId(accountId);
        metric.setMetricName(metricName);
        metric.setNamespace(namespace);
        metric.setDimensions(dimensionsPermutation);
        metric.setMetricType(metricType);
        metrics.add(metric);
    }
    return metrics;
}