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

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

Introduction

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

Prototype

public static <E> SetView<E> union(final Set<? extends E> set1, final Set<? extends E> set2) 

Source Link

Document

Returns an unmodifiable view of the union of two sets.

Usage

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

/**
 * Creates a int pattern needed for the join operation.
 * /*ww w.  ja  v a2s.  co  m*/
 * @param baseSet
 *            all parameters of this set will be kept
 * @param joiningSet
 *            new parameters from this set will join
 * @return
 */
protected static int[] getExtensionPattern(Set<Parameter<?>> baseSet, Set<Parameter<?>> joiningSet) {
    final List<Integer> result = new ArrayList<Integer>();
    final Set<Integer> baseParameterIndexSet = toParameterIndexSet(baseSet);
    final int[] joinedArray = toParameterMask(Sets.union(baseSet, joiningSet));
    for (int parameterIndex : joinedArray) {
        if (baseParameterIndexSet.contains(parameterIndex)) {
            result.add(parameterIndex);
        } else {
            result.add(-1);
        }
    }
    return toPrimitiveIntegerArray(result);
}

From source file:net.navatwo.jfxproperties.PropertyObject.java

/**
 * Initialize a {@link PropertyObject}.//from  w  w  w . j av  a2s  .c o m
 * <br/>
 * <p>
 * This should only be called from {@link Builder}.
 *
 * @param fields  Fields found in the hierarchy
 * @param methods Methods found in the hierarchy
 */
@SuppressWarnings("unchecked")
PropertyObject(TypeToken<T> base, Collection<? extends PropertyObject<? super T>> supers,
        Set<String> ignoredProperties, Map<String, TypeToken<?>> types, Map<String, Field> fields,
        Map<String, EnumMap<MethodType, Invokable<T, ?>>> methods) {
    this.base = checkNotNull(base, "base == null");
    this.hashCode = base.hashCode();
    this.supers = checkNotNull(supers, "supers == null");

    // Collect all of the properties from the immediate super collectors, these will have been initialized with
    // their super ignored properties as well.
    ImmutableSortedSet.Builder<String> ignoredPropertiesBuilder = ImmutableSortedSet.naturalOrder();
    ignoredPropertiesBuilder.addAll(ignoredProperties);
    supers.stream().flatMap(s -> s.getIgnoredProperties().stream()).forEach(ignoredPropertiesBuilder::add);
    this.ignoredProperties = ignoredPropertiesBuilder.build();

    // now we need to go through and create a mapping of property names to the accessing methods/fields
    // do a union on the keys this gives us all the property names that have been found
    ImmutableMap.Builder<String, PropertyInfo<?>> propertyMapBuilder = ImmutableMap.builder();
    Sets.union(methods.keySet(), fields.keySet()).stream()
            .filter(propName -> !this.ignoredProperties.contains(propName)).forEach(propName -> {
                // Now build the appropriate PropertyInfo<> implementation dependant on the type of the Field.
                // We can use the primitive versions when it will be faster for them to execute later.

                TypeToken<?> propType = types.get(propName).unwrap();

                EnumMap<MethodType, Invokable<T, ?>> mmap = methods.getOrDefault(propName,
                        new EnumMap<>(MethodType.class));

                Field field = fields.get(propName);
                Invokable<T, ? extends ReadOnlyProperty<?>> accessor = (Invokable<T, ? extends ReadOnlyProperty<?>>) mmap
                        .get(MethodType.ACCESSOR);
                Invokable<T, ?> getter = mmap.get(MethodType.GETTER);
                Invokable<T, Void> setter = (Invokable<T, Void>) mmap.get(MethodType.SETTER);

                if (getter != null || setter != null || accessor != null) {

                    PropertyInfoExtractor piExtract = new PropertyInfoExtractor(propName, base, propType, field,
                            getter, setter, accessor);
                    TypeAcceptor.accept(propType, piExtract);

                    propertyMapBuilder.put(propName, piExtract.getPropertyInfo());
                }
            });

    this.localProperties = propertyMapBuilder.build();
    this.thisNames = ImmutableSortedSet.copyOf(localProperties.keySet());

    supers.stream().flatMap(s -> s.getProperties().entrySet().stream())
            .filter(e -> !this.thisNames.contains(e.getKey()))
            .filter(e -> !this.ignoredProperties.contains(e.getKey()))
            .forEach(e -> propertyMapBuilder.put(e.getKey(), e.getValue()));

    // Now create the immutable structures required and store them.
    allProperties = propertyMapBuilder.build();
    allNames = ImmutableSortedSet.copyOf(allProperties.keySet());
}

From source file:c5db.interfaces.replication.QuorumConfiguration.java

private QuorumConfiguration(Collection<Long> prevPeers, Collection<Long> nextPeers) {
    this.isTransitional = true;
    this.prevPeers = ImmutableSet.copyOf(prevPeers);
    this.nextPeers = ImmutableSet.copyOf(nextPeers);
    this.allPeers = Sets.union(this.prevPeers, this.nextPeers).immutableCopy();
}

From source file:com.facebook.buck.core.model.targetgraph.AbstractTargetNode.java

/** @return all targets which must be built before this one can be. */
public Set<BuildTarget> getBuildDeps() {
    return Sets.union(getDeclaredDeps(), getExtraDeps());
}

From source file:org.apache.beam.fn.harness.DoFnPTransformRunnerFactory.java

@Override
public final RunnerT createRunnerForPTransform(PipelineOptions pipelineOptions,
        BeamFnDataClient beamFnDataClient, BeamFnStateClient beamFnStateClient, String ptransformId,
        PTransform pTransform, Supplier<String> processBundleInstructionId,
        Map<String, PCollection> pCollections, Map<String, RunnerApi.Coder> coders,
        Map<String, RunnerApi.WindowingStrategy> windowingStrategies,
        ListMultimap<String, FnDataReceiver<WindowedValue<?>>> pCollectionIdsToConsumers,
        Consumer<ThrowingRunnable> addStartFunction, Consumer<ThrowingRunnable> addFinishFunction,
        BundleSplitListener splitListener) {
    Context<FnInputT, OutputT> context = new Context<>(pipelineOptions, beamFnStateClient, ptransformId,
            pTransform, processBundleInstructionId, pCollections, coders, windowingStrategies,
            pCollectionIdsToConsumers, splitListener);

    RunnerT runner = createRunner(context);

    // Register the appropriate handlers.
    addStartFunction.accept(runner::startBundle);
    Iterable<String> mainInput = Sets.difference(pTransform.getInputsMap().keySet(),
            Sets.union(context.parDoPayload.getSideInputsMap().keySet(),
                    context.parDoPayload.getTimerSpecsMap().keySet()));
    for (String localInputName : mainInput) {
        pCollectionIdsToConsumers.put(pTransform.getInputsOrThrow(localInputName),
                (FnDataReceiver) (FnDataReceiver<WindowedValue<TransformInputT>>) runner::processElement);
    }// ww w.ja va2  s  . c o  m

    // Register as a consumer for each timer PCollection.
    for (String localName : context.parDoPayload.getTimerSpecsMap().keySet()) {
        TimeDomain timeDomain = DoFnSignatures
                .getTimerSpecOrThrow(context.doFnSignature.timerDeclarations().get(localName), context.doFn)
                .getTimeDomain();
        pCollectionIdsToConsumers.put(pTransform.getInputsOrThrow(localName),
                timer -> runner.processTimer(localName, timeDomain, (WindowedValue<KV<Object, Timer>>) timer));
    }

    addFinishFunction.accept(runner::finishBundle);
    return runner;
}

From source file:com.google.enterprise.connector.util.filter.SkipDocumentFilter.java

@Override
public Set<String> getPropertyNames(Document source) throws RepositoryException {
    Preconditions.checkState(propertyName != null, "must set propertyName");
    return Sets.union(source.getPropertyNames(), ImmutableSet.of(propertyName));
}

From source file:grakn.core.server.kb.concept.ConceptUtils.java

/**
 * perform an answer merge with optional explanation
 * NB:assumes answers are compatible (concept corresponding to join vars if any are the same)
 *
 * @return merged answer//  www.  ja v  a2s .co m
 */
public static ConceptMap mergeAnswers(ConceptMap answerA, ConceptMap answerB) {
    if (answerB.isEmpty())
        return answerA;
    if (answerA.isEmpty())
        return answerB;

    Sets.SetView<Variable> varUnion = Sets.union(answerA.vars(), answerB.vars());
    Set<Variable> varIntersection = Sets.intersection(answerA.vars(), answerB.vars());
    Map<Variable, Concept> entryMap = Sets.union(answerA.map().entrySet(), answerB.map().entrySet()).stream()
            .filter(e -> !varIntersection.contains(e.getKey()))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
    varIntersection.forEach(var -> {
        Concept concept = answerA.get(var);
        Concept otherConcept = answerB.get(var);
        if (concept.equals(otherConcept))
            entryMap.put(var, concept);
        else {
            if (concept.isSchemaConcept() && otherConcept.isSchemaConcept() && !ConceptUtils
                    .areDisjointTypes(concept.asSchemaConcept(), otherConcept.asSchemaConcept(), false)) {
                entryMap.put(var, Iterables.getOnlyElement(ConceptUtils.topOrMeta(
                        Sets.newHashSet(concept.asSchemaConcept(), otherConcept.asSchemaConcept()))));
            }
        }
    });
    if (!entryMap.keySet().equals(varUnion))
        return new ConceptMap();
    return new ConceptMap(entryMap, answerA.explanation());
}

From source file:com.facebook.buck.core.model.targetgraph.impl.AbstractImmutableTargetNode.java

/**
 * @return all targets which must be present in the TargetGraph before this one can be transformed
 *     into a BuildRule.//from w  ww.ja  v  a2s.c om
 */
@Override
public Set<BuildTarget> getParseDeps() {
    return Sets.union(getBuildDeps(), getTargetGraphOnlyDeps());
}

From source file:com.b2international.commons.hierarchy.Hierarchy.java

private SetView<M> doGetAllMembers() {
    return Sets.union(topLevelMembers, childToParentMap.keySet());
}

From source file:com.opengamma.strata.calc.runner.DerivedCalculationFunctionWrapper.java

@Override
public Map<Measure, Result<?>> calculate(T target, Set<Measure> measures, CalculationParameters parameters,
        ScenarioMarketData marketData, ReferenceData refData) {

    // The caller didn't ask for the derived measure so just return the measures calculated by the delegate
    Measure derivedMeasure = derivedFunction.measure();
    if (!measures.contains(derivedMeasure)) {
        return delegate.calculate(target, measures, parameters, marketData, refData);
    }/*from ww  w  .  j  a  v  a 2  s.  com*/
    // Add the measures required to calculate the derived measure to the measures requested by the caller
    Set<Measure> allRequiredMeasures = Sets.union(measures, derivedFunction.requiredMeasures());
    Set<Measure> requiredMeasures = Sets.difference(allRequiredMeasures, ImmutableSet.of(derivedMeasure));
    Map<Measure, Result<?>> delegateResults = delegate.calculate(target, requiredMeasures, parameters,
            marketData, refData);

    // Calculate the derived measure
    Result<?> result = calculateMeasure(target, delegateResults, parameters, marketData, refData);

    // The results containing only the requested measures and not including extra measures that were inserted above
    // Also filter out any results for calculationFunction.measure(). There will be failures from functions below
    // that don't support that measure.
    Map<Measure, Result<?>> requestedResults = MapStream.of(delegateResults).filterKeys(measures::contains)
            .filterKeys(measure -> !measure.equals(derivedMeasure)).toMap();

    return ImmutableMap.<Measure, Result<?>>builder().put(derivedMeasure, result).putAll(requestedResults)
            .build();
}