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:ai.grakn.graql.internal.query.QueryOperationExecutor.java

/**
 * Produce a valid ordering of the properties by using the given dependency information.
 *
 * <p>/*  w  w  w. j a  v  a 2s. c  om*/
 *     This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering.
 * </p>
 */
private ImmutableList<VarAndProperty> sortProperties() {
    ImmutableList.Builder<VarAndProperty> sorted = ImmutableList.builder();

    // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified
    // we should always also modify invertedDependencies (and vice-versa).
    Multimap<VarAndProperty, VarAndProperty> dependencies = HashMultimap.create(this.dependencies);
    Multimap<VarAndProperty, VarAndProperty> invertedDependencies = HashMultimap.create();
    Multimaps.invertFrom(dependencies, invertedDependencies);

    Queue<VarAndProperty> propertiesWithoutDependencies = new ArrayDeque<>(
            Sets.filter(properties, property -> dependencies.get(property).isEmpty()));

    VarAndProperty property;

    // Retrieve the next property without any dependencies
    while ((property = propertiesWithoutDependencies.poll()) != null) {
        sorted.add(property);

        // We copy this into a new list because the underlying collection gets modified during iteration
        Collection<VarAndProperty> dependents = Lists.newArrayList(invertedDependencies.get(property));

        for (VarAndProperty dependent : dependents) {
            // Because the property has been removed, the dependent no longer needs to depend on it
            dependencies.remove(dependent, property);
            invertedDependencies.remove(property, dependent);

            boolean hasNoDependencies = dependencies.get(dependent).isEmpty();

            if (hasNoDependencies) {
                propertiesWithoutDependencies.add(dependent);
            }
        }
    }

    if (!dependencies.isEmpty()) {
        // This means there must have been a loop. Pick an arbitrary remaining var to display
        Var var = dependencies.keys().iterator().next().var();
        throw GraqlQueryException.insertRecursive(printableRepresentation(var));
    }

    return sorted.build();
}

From source file:com.kolich.curacao.mappers.MapperTable.java

private final ImmutableMultimap<Class<?>, ControllerArgumentMapper<?>> buildArgumentMapperTable(
        final Set<Class<?>> mapperSet) {
    // Using a LinkedHashMultimap internally because insertion order is
    // very important in this case.
    final Multimap<Class<?>, ControllerArgumentMapper<?>> mappers = LinkedHashMultimap.create(); // Preserves order
    // Filter the incoming mapper set to only argument mappers.
    final Set<Class<?>> filtered = Sets.filter(mapperSet,
            Predicates.assignableFrom(ControllerArgumentMapper.class));
    logger__.debug("Found {} argument mappers annotated with @{}", filtered.size(), MAPPER_ANNOTATION_SN);
    // For each discovered mapper class...
    for (final Class<?> mapper : filtered) {
        logger__.debug("Found @{}: argument mapper {}", MAPPER_ANNOTATION_SN, mapper.getCanonicalName());
        try {/*  www  .j  a  v  a2 s .  c  om*/
            // Locate a single constructor worthy of injecting with
            // components, if any.  May be null.
            final Constructor<?> ctor = getInjectableConstructor(mapper);
            ControllerArgumentMapper<?> instance = null;
            if (ctor == null) {
                // Class.newInstance() is evil, so we do the ~right~ thing
                // here to instantiate a new instance of the mapper using
                // the preferred getConstructor() idiom.
                instance = (ControllerArgumentMapper<?>) mapper.getConstructor().newInstance();
            } else {
                final Class<?>[] types = ctor.getParameterTypes();
                final Object[] params = new Object[types.length];
                for (int i = 0, l = types.length; i < l; i++) {
                    params[i] = componentTable_.getComponentForType(types[i]);
                }
                instance = (ControllerArgumentMapper<?>) ctor.newInstance(params);
            }
            // Note the key in the map is the parameterized generic type
            // hanging off the mapper.
            mappers.put(getGenericType(mapper), instance);
        } catch (Exception e) {
            logger__.error("Failed to instantiate mapper instance: {}", mapper.getCanonicalName(), e);
        }
    }
    // Add the "default" mappers to the ~end~ of the immutable hash multi map.
    // This essentially means that default argument mappers (the ones
    // provided by this library) are found & called after any user registered
    // mappers.
    mappers.putAll(defaultArgMappers__);
    return ImmutableMultimap.copyOf(mappers);
}

From source file:grakn.core.graql.executor.WriteExecutor.java

/**
 * Produce a valid ordering of the properties by using the given dependency information.
 * This method uses a topological sort (Kahn's algorithm) in order to find a valid ordering.
 *//*  w  ww  .  j av a 2  s  .  c  o m*/
private ImmutableList<Writer> sortedWriters() {
    ImmutableList.Builder<Writer> sorted = ImmutableList.builder();

    // invertedDependencies is intended to just be a 'view' on dependencies, so when dependencies is modified
    // we should always also modify invertedDependencies (and vice-versa).
    Multimap<Writer, Writer> dependencies = HashMultimap.create(this.dependencies);
    Multimap<Writer, Writer> invertedDependencies = HashMultimap.create();
    Multimaps.invertFrom(dependencies, invertedDependencies);

    Queue<Writer> writerWithoutDependencies = new ArrayDeque<>(
            Sets.filter(writers, property -> dependencies.get(property).isEmpty()));

    Writer property;

    // Retrieve the next property without any dependencies
    while ((property = writerWithoutDependencies.poll()) != null) {
        sorted.add(property);

        // We copy this into a new list because the underlying collection gets modified during iteration
        Collection<Writer> dependents = Lists.newArrayList(invertedDependencies.get(property));

        for (Writer dependent : dependents) {
            // Because the property has been removed, the dependent no longer needs to depend on it
            dependencies.remove(dependent, property);
            invertedDependencies.remove(property, dependent);

            boolean hasNoDependencies = dependencies.get(dependent).isEmpty();

            if (hasNoDependencies) {
                writerWithoutDependencies.add(dependent);
            }
        }
    }

    if (!dependencies.isEmpty()) {
        // This means there must have been a loop. Pick an arbitrary remaining var to display
        Variable var = dependencies.keys().iterator().next().var();
        throw GraqlSemanticException.insertRecursive(printableRepresentation(var));
    }

    return sorted.build();
}

From source file:org.trnltk.morphology.contextless.parser.ContextlessMorphologicParser.java

private Set<SuffixFormGraphSuffixEdge> getApplicableSuffixesOfNodeForMorphemeContainer(
        final SuffixFormGraphNode node, final MorphemeContainer morphemeContainer) {
    if (logger.isDebugEnabled()) {
        logger.debug("  Finding applicable suffixes for morpheme_container from node " + node + " : "
                + morphemeContainer);//from  ww w .  ja  va 2 s  .  c o m
        logger.debug("   Found outputs " + node.getEdges());
    }

    Set<SuffixFormGraphSuffixEdge> edges = node.getEdges();

    edges = Sets.filter(edges, new Predicate<SuffixFormGraphSuffixEdge>() {
        @Override
        public boolean apply(SuffixFormGraphSuffixEdge input) {
            final String appliedSuffixForm = input.getSuffixFormApplication().getActualSuffixForm();
            return morphemeContainer.getRemainingSurface().startsWith(appliedSuffixForm);
        }
    });
    if (logger.isDebugEnabled())
        logger.debug("   Filtered out suffix forms which are not beginning of remaining surface "
                + morphemeContainer.getSuffixesSinceDerivationSuffix() + " : " + edges);

    edges = Sets.filter(edges, new Predicate<SuffixFormGraphSuffixEdge>() {
        @Override
        public boolean apply(SuffixFormGraphSuffixEdge input) {
            return !morphemeContainer.getSuffixesSinceDerivationSuffix()
                    .contains(input.getSuffixFormApplication().getSuffixForm().getSuffix());
        }
    });
    if (logger.isDebugEnabled())
        logger.debug("   Filtered out the applied suffixes since last derivation "
                + morphemeContainer.getSuffixesSinceDerivationSuffix() + " : " + edges);

    return edges;
}

From source file:org.batoo.jpa.common.reflect.ReflectHelper.java

/**
 * Logs warnings for annotations that were ignored.
 * /*www .ja  v  a2  s  . c  o  m*/
 * @param logger
 *            the logger to log the warnings.
 * @param member
 *            the member
 * @param annotations
 *            the set of annotations allowed
 * 
 * @since $version
 * @author hceylan
 */
public static void warnAnnotations(BLogger logger, Member member,
        final Set<Class<? extends Annotation>> annotations) {
    final Set<Annotation> existing;

    if (member instanceof Field) {
        existing = Sets.newHashSet(((Field) member).getAnnotations());
    } else {
        existing = Sets.newHashSet(((Method) member).getAnnotations());
    }

    final Set<Annotation> filtered = Sets.filter(existing, new Predicate<Annotation>() {

        @Override
        public boolean apply(Annotation input) {
            for (final Annotation annotation : existing) {
                if (annotations.contains(annotation.annotationType())) {
                    return false;
                }
            }

            return true;
        }
    });

    if (filtered.size() > 0) {
        logger.warn("Following annotations on {0} were ignored: {1}", ReflectHelper.createMemberName(member),
                Joiner.on(", ").join(filtered));
    }
}

From source file:org.voltcore.agreement.MeshArbiter.java

protected Map<Long, Long> getSafeTxnIdsForSites(Set<Long> hsIds) {
    ImmutableMap.Builder<Long, Long> safeb = ImmutableMap.builder();
    for (long h : Sets.filter(hsIds, not(equalTo(m_hsId)))) {
        safeb.put(h, m_meshAide.getNewestSafeTransactionForInitiator(h));
    }//from ww  w  . j ava 2 s.  c o  m
    return safeb.build();
}

From source file:gov.nih.nci.firebird.data.InvestigatorProfile.java

/**
 * Returns the <code>OrganizationAssociations</code> that correspond to the requested type.
 *
 * @param type retrieve associations of this type
 * @return the matching associations./*  ww w. j a  v a  2 s. c  o m*/
 */
public Set<OrganizationAssociation> getOrganizationAssociations(final OrganizationRoleType type) {
    return Sets.filter(getOrganizationAssociations(), new Predicate<OrganizationAssociation>() {
        @Override
        public boolean apply(OrganizationAssociation organizationAssociation) {
            return type.equals(organizationAssociation.getType());
        }
    });

}

From source file:org.easyrec.store.dao.core.types.impl.AssocTypeDAOMysqlImpl.java

@LongCacheable
public Set<String> getTypes(Integer tenantId, Boolean visible) {
    Preconditions.checkNotNull(tenantId, "missing constraints: missing 'tenantId'");

    Object[] args = { tenantId };
    int[] argTypes = { Types.INTEGER };

    StringBuilder sqlQuery = new StringBuilder("SELECT ");
    sqlQuery.append(DEFAULT_NAME_COLUMN_NAME);
    sqlQuery.append(" FROM ");
    sqlQuery.append(DEFAULT_TABLE_NAME);
    sqlQuery.append(" WHERE ");
    sqlQuery.append(DEFAULT_TENANT_COLUMN_NAME);
    sqlQuery.append("=?");

    if (visible != null) {
        sqlQuery.append(" AND ").append(DEFAULT_VISIBLE_COLUMN_NAME);
        sqlQuery.append("=?");

        args = ObjectArrays.concat(args, visible);
        argTypes = Ints.concat(argTypes, new int[] { Types.BIT });
    }//from   www.  j  a v  a2s.  co m

    sqlQuery.append(" ORDER BY ");
    sqlQuery.append(DEFAULT_NAME_COLUMN_NAME);

    Set<String> result = Sets
            .newTreeSet(getJdbcTemplate().queryForList(sqlQuery.toString(), args, argTypes, String.class));

    return Sets.newTreeSet(Sets.filter(result, Predicates.notNull()));
}

From source file:org.voltcore.agreement.MeshArbiter.java

/**
 * Send one message to each surviving execution site providing this site's
 * multi-partition commit point and this site's safe txnid
 * (the receiver will filter the later for its
 * own partition). Do this once for each failed initiator that we know about.
 * Sends all data all the time to avoid a need for request/response.
 *//*from w w w .  j  a  v a2  s  .c  om*/
private void discoverGlobalFaultData_send(Set<Long> hsIds) {
    Set<Long> dests = Sets.filter(m_seeker.getSurvivors(), not(equalTo(m_hsId)));

    SiteFailureMessage.Builder msgBuilder = SiteFailureMessage.builder().survivors(m_seeker.getSurvivors())
            .failures(m_inTrouble.keySet()).safeTxnIds(getSafeTxnIdsForSites(hsIds));

    SiteFailureMessage sfm = msgBuilder.build();
    sfm.m_sourceHSId = m_hsId;

    updateFailedSitesLedger(hsIds, sfm);
    m_seeker.add(sfm);

    m_mailbox.send(Longs.toArray(dests), sfm);

    m_recoveryLog.info("Agreement, Sending survivors " + sfm);
}

From source file:org.terasology.logic.console.commandSystem.AbstractCommand.java

@Override
public final Set<String> suggest(final String currentValue, List<String> rawParameters, EntityRef sender)
        throws CommandSuggestionException {
    //Generate an array to be used as a parameter in the 'suggest' method
    Object[] processedParameters;

    try {//ww w . j a  va 2s . co m
        processedParameters = processParametersMethod(rawParameters, sender);
    } catch (CommandParameterParseException e) {
        String warning = "Invalid parameter '" + e.getParameter() + "'";
        String message = e.getMessage();

        if (message != null) {
            warning += ": " + message;
        }

        throw new CommandSuggestionException(warning);
    }

    //Get the suggested parameter to compare the result with
    CommandParameter suggestedParameter = null;
    Iterator<CommandParameter> paramIter = commandParameters.iterator();

    for (Object processedParameter : processedParameters) {
        if (sender.equals(processedParameter)) {
            continue;
        }
        if (processedParameter == null) {
            suggestedParameter = paramIter.next();
            break;
        }
        paramIter.next();
    }

    if (suggestedParameter == null) {
        return Sets.newHashSet();
    }

    Set<Object> result = null;

    result = suggestedParameter.suggest(sender, processedParameters);

    if (result == null) {
        return Sets.newHashSet();
    }

    Class<?> requiredClass = suggestedParameter.getType();

    for (Object resultComponent : result) {
        if (resultComponent == null && requiredClass.isPrimitive()) {
            throw new CommandSuggestionException(
                    "The 'suggest' method of command class " + getClass().getCanonicalName()
                            + " returns a collection containing an invalid type. Required: "
                            + requiredClass.getCanonicalName() + "; provided: null");
        } else if (resultComponent != null && !requiredClass.isAssignableFrom(resultComponent.getClass())) {
            throw new CommandSuggestionException(
                    "The 'suggest' method of command class " + getClass().getCanonicalName()
                            + " returns a collection containing an invalid type. Required: "
                            + requiredClass.getCanonicalName() + "; provided: "
                            + resultComponent.getClass().getCanonicalName());
        }
    }

    Set<String> stringSuggestions = convertToString(result, suggestedParameter);

    //Only return results starting with currentValue
    return Sets.filter(stringSuggestions,
            input -> input != null && (currentValue == null || input.startsWith(currentValue)));
}