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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the intersection of two sets.

Usage

From source file:ai.grakn.graql.internal.reasoner.query.QueryAnswerStream.java

/**
 * lazy stream join with fast lookup from inverse answer map
 * @param stream left stream operand//w ww  .ja  va  2  s  . c  o  m
 * @param stream2 right stream operand
 * @param stream2InverseMap inverse map of right operand from cache
 * @param joinVars intersection on variables of two streams
 * @return joined stream
 */
public static Stream<Answer> joinWithInverse(Stream<Answer> stream, Stream<Answer> stream2,
        Map<Pair<Var, Concept>, Set<Answer>> stream2InverseMap, ImmutableSet<Var> joinVars,
        boolean explanation) {
    if (joinVars.isEmpty()) {
        LazyAnswerIterator l2 = new LazyAnswerIterator(stream2);
        return stream.flatMap(a1 -> l2.stream().map(a -> a.merge(a1, explanation)));
    }
    return stream.flatMap(a1 -> {
        Iterator<Var> vit = joinVars.iterator();
        Set<Answer> matchAnswers = findMatchingAnswers(a1, stream2InverseMap, vit.next());
        while (vit.hasNext()) {
            matchAnswers = Sets.intersection(matchAnswers,
                    findMatchingAnswers(a1, stream2InverseMap, vit.next()));
        }
        return matchAnswers.stream().map(a -> a.merge(a1, explanation));
    });
}

From source file:com.google.gerrit.solr.SolrChangeIndex.java

@Override
public ChangeDataSource getSource(Predicate<ChangeData> p, int start, int limit) throws QueryParseException {
    Set<Change.Status> statuses = IndexRewriteImpl.getPossibleStatus(p);
    List<SolrServer> indexes = Lists.newArrayListWithCapacity(2);
    if (!Sets.intersection(statuses, OPEN_STATUSES).isEmpty()) {
        indexes.add(openIndex);//ww w .  j  a va 2s. c  o m
    }
    if (!Sets.intersection(statuses, CLOSED_STATUSES).isEmpty()) {
        indexes.add(closedIndex);
    }
    return new QuerySource(indexes, queryBuilder.toQuery(p), start, limit, getSorts());
}

From source file:com.netflix.paas.dao.astyanax.SimpleReverseIndexer.java

@Override
public Collection<String> findIntersection(Map<String, String> tags) throws IndexerException {
    Set<String> ids = Sets.newHashSet();

    MutationBatch mb = keyspace.prepareMutationBatch();
    try {/*w w  w .j a  v a 2 s  . c  o m*/
        boolean first = true;
        Set<Entry<String, String>> elements = tags.entrySet();

        for (Row<String, IndexEntry> row : keyspace.prepareQuery(indexCf).getKeySlice(fieldsToSet(tags))
                .execute().getResult()) {
            Set<String> rowIds = Sets.newHashSet();
            ColumnListMutation<IndexEntry> mrow = null;
            IndexEntry previousEntry = null;
            for (Column<IndexEntry> column : row.getColumns()) {
                IndexEntry entry = column.getName();
                if (previousEntry != null && entry.id == previousEntry.id) {
                    if (mrow == null)
                        mrow = mb.withRow(indexCf, row.getKey());
                    mrow.deleteColumn(previousEntry);
                }

                rowIds.add(entry.id);
            }

            if (first) {
                first = false;
                ids = rowIds;
            } else {
                ids = Sets.intersection(ids, rowIds);
                if (ids.isEmpty())
                    return ids;
            }
        }
    } catch (ConnectionException e) {
        throw new IndexerException("Failed to get tags : " + tags, e);
    } finally {
        try {
            mb.execute();
        } catch (ConnectionException e) {
            // OK to ignore
        }
    }
    return ids;
}

From source file:gobblin.data.management.policy.CombineSelectionPolicy.java

private static Set<DatasetVersion> intersectDatasetVersions(Collection<Set<DatasetVersion>> sets) {
    if (sets.size() <= 0) {
        return Sets.newHashSet();
    }//from  ww w .  j  a  v a  2  s  . c  o m
    Iterator<Set<DatasetVersion>> it = sets.iterator();
    Set<DatasetVersion> outputSet = it.next();
    while (it.hasNext()) {
        outputSet = Sets.intersection(outputSet, it.next());
    }
    return outputSet;
}

From source file:org.tensorics.core.tensor.operations.InnerTensorOperation.java

@Override
public Tensor<V> perform(Tensor<V> left, Tensor<V> right) {
    checkNotNull(left, "left tensor must not be null!");
    checkNotNull(right, "right tensor must not be null!");

    List<CoContraDimensionPair> allPairs = CoContraDimensionPairs.coContraPairsOf(left.shape(), right.shape());
    List<CoContraDimensionPair> pairsToReduce = CoContraDimensionPairs.chooseOnePerContravariantPart(allPairs);
    Set<Class<?>> dimensionsNotToBroadcast = CoContraDimensionPairs.allDimensionsIn(pairsToReduce);

    TensorPair<V> broadcasted = broadcast(left, right, dimensionsNotToBroadcast);

    Set<Class<?>> leftDimensionsToReduce = CoContraDimensionPairs.leftDimensionsIn(pairsToReduce);
    Set<Class<?>> rightDimensionsToReduce = CoContraDimensionPairs.rightDimensionsIn(pairsToReduce);

    Set<Class<?>> remainingLeftDimensions = Sets
            .difference(broadcasted.left().shape().dimensionSet(), leftDimensionsToReduce).immutableCopy();
    Set<Class<?>> remainingRightDimensions = Sets
            .difference(broadcasted.right().shape().dimensionSet(), rightDimensionsToReduce).immutableCopy();

    Set<Class<?>> targetDimensions = Sets.union(remainingLeftDimensions, remainingRightDimensions)
            .immutableCopy();/*from www  . j a  v a  2  s.c om*/
    Set<Class<?>> remainingCommonDimensions = Sets.intersection(remainingLeftDimensions,
            remainingRightDimensions);

    /*
     * produce a multimap from positions, consisting of all but the unique right dimensions to positions.
     */
    Set<Class<?>> uniqueLeftDimensions = Sets.difference(remainingLeftDimensions, remainingCommonDimensions);
    Set<Class<?>> uniqueRightDimensions = Sets.difference(remainingRightDimensions, remainingCommonDimensions);
    Multimap<Position, Position> nonUniqueToRightPositions = Positions
            .mapByStripping(broadcasted.right().shape().positionSet(), uniqueRightDimensions);

    DimensionStripper stripper = Positions.stripping(uniqueLeftDimensions);

    DimensionStripper targetLeftStripper = Positions.stripping(leftDimensionsToReduce);
    DimensionStripper targetRightStripper = Positions.stripping(rightDimensionsToReduce);

    ImmutableMultimap.Builder<Position, PositionPair> builder = ImmutableMultimap.builder();
    for (Position leftPosition : broadcasted.left().shape().positionSet()) {
        Position remainingLeftPosition = targetLeftStripper.apply(leftPosition);

        Position nonUniqueLeftPosition = stripper.apply(leftPosition);
        Position nonUniqueRightPosition = CoContraDimensionPairs.convertToRight(nonUniqueLeftPosition,
                pairsToReduce);
        Collection<Position> rightPositions = nonUniqueToRightPositions.get(nonUniqueRightPosition);
        for (Position rightPosition : rightPositions) {
            Position remainingRightPosition = targetRightStripper.apply(rightPosition);
            Position targetPosition = Positions.combineDimensions(remainingLeftPosition, remainingRightPosition,
                    targetDimensions);
            builder.put(targetPosition, PositionPair.fromLeftRight(leftPosition, rightPosition));
        }
    }

    Multimap<Position, PositionPair> targetPositionToPairs = builder.build();

    ListMultimap<Position, ValuePair<V>> valuePairs = broadcasted.mapValues(targetPositionToPairs);

    ListMultimap<Position, V> targetPositionToValueSet = Operations.mapAll(valuePairs, elementOperation);

    Map<Position, V> result = IterableOperations.reduce(targetPositionToValueSet, reductionOperation);

    ContextPropagationStrategy cps = optionRegistry.get(ContextPropagationStrategy.class);
    Position resultingContext = cps.contextForLeftRight(left.context(), right.context());

    TensorBuilder<V> finalBuilder = Tensorics.builder(targetDimensions);
    finalBuilder.putAll(result);
    finalBuilder.context(resultingContext);
    return finalBuilder.build();
}

From source file:com.google.devtools.build.xcode.plmerge.PlistMerging.java

/**
 * Generates a Plistmerging combining values from sourceFiles and immutableSourceFiles, and
 * modifying them based on subsitutions and keysToRemoveIfEmptyString.
 *//*from   ww w .ja  v a 2  s  .  c  o m*/
public static PlistMerging from(List<Path> sourceFiles, List<Path> immutableSourceFiles,
        Map<String, String> substitutions, KeysToRemoveIfEmptyString keysToRemoveIfEmptyString,
        String executableName) throws IOException {
    NSDictionary merged = PlistMerging.merge(sourceFiles);
    NSDictionary immutableEntries = PlistMerging.merge(immutableSourceFiles);
    Set<String> conflictingEntries = Sets.intersection(immutableEntries.keySet(), merged.keySet());

    Preconditions.checkArgument(conflictingEntries.isEmpty(),
            "The following plist entries may not be overridden, but are present in more than one "
                    + "of the input lists: %s",
            conflictingEntries);
    merged.putAll(immutableEntries);

    for (Map.Entry<String, NSObject> entry : merged.entrySet()) {
        if (entry.getValue().toJavaObject() instanceof String) {
            String newValue = substituteEnvironmentVariable(substitutions,
                    (String) entry.getValue().toJavaObject());
            merged.put(entry.getKey(), newValue);
        }
    }

    for (String key : keysToRemoveIfEmptyString) {
        if (Equaling.of(Mapping.of(merged, key), Optional.<NSObject>of(new NSString("")))) {
            merged.remove(key);
        }
    }

    // Info.plist files must contain a valid CFBundleVersion and a valid CFBundleShortVersionString,
    // or it will be rejected by Apple.
    // A valid Bundle Version is 18 characters or less, and only contains [0-9.]
    // We know we have an info.plist file as opposed to a strings file if the immutableEntries
    // have any values set.
    // TODO(bazel-team): warn user if we replace their values.
    if (!immutableEntries.isEmpty()) {
        Pattern versionPattern = Pattern.compile("[^0-9.]");
        if (!merged.containsKey(BUNDLE_VERSION_PLIST_KEY)) {
            merged.put(BUNDLE_VERSION_PLIST_KEY, BUNDLE_VERSION_DEFAULT);
        } else {
            NSObject nsVersion = merged.get(BUNDLE_VERSION_PLIST_KEY);
            String version = (String) nsVersion.toJavaObject();
            if (version.length() > 18 || versionPattern.matcher(version).find()) {
                merged.put(BUNDLE_VERSION_PLIST_KEY, BUNDLE_VERSION_DEFAULT);
            }
        }
        if (!merged.containsKey(BUNDLE_SHORT_VERSION_STRING_PLIST_KEY)) {
            merged.put(BUNDLE_SHORT_VERSION_STRING_PLIST_KEY, BUNDLE_SHORT_VERSION_STRING_DEFAULT);
        } else {
            NSObject nsVersion = merged.get(BUNDLE_SHORT_VERSION_STRING_PLIST_KEY);
            String version = (String) nsVersion.toJavaObject();
            if (version.length() > 18 || versionPattern.matcher(version).find()) {
                merged.put(BUNDLE_SHORT_VERSION_STRING_PLIST_KEY, BUNDLE_SHORT_VERSION_STRING_DEFAULT);
            }
        }
    }

    PlistMerging result = new PlistMerging(merged);

    if (executableName != null) {
        result.setExecutableName(executableName);
    }

    return result;
}

From source file:com.opengamma.engine.view.calc.ViewComputationJobDataProvider.java

/**
 * Unsubscribes from market data./*from w  w  w.java  2 s . c  o  m*/
 * @param requirements The subscriptions that should be removed, not null
 */
/* package */ void unsubscribe(Set<ValueRequirement> requirements) {
    ArgumentChecker.notNull(requirements, "requirements");
    Set<ValueRequirement> remainingReqs = Sets.newHashSet(requirements);
    for (int i = 0; i < _subscriptions.size(); i++) {
        Set<ValueRequirement> providerSubscriptions = _subscriptions.get(i);
        Set<ValueRequirement> subsToRemove = Sets.intersection(remainingReqs, providerSubscriptions);
        if (!subsToRemove.isEmpty()) {
            _providers.get(i).unsubscribe(subsToRemove);
            providerSubscriptions.removeAll(subsToRemove);
            remainingReqs.removeAll(subsToRemove);
        }
    }
}

From source file:org.diqube.execution.steps.FilterRequestedColumnsAndActiveRowIdsStep.java

/**
 * Filters all values of all columns that have one of the specified rowIds and informs {@link ColumnValueConsumer}s
 * about them.//from   w  w  w . j  av  a2 s.co m
 */
private void processValues(Map<String, Map<Long, Object>> values, Set<Long> rowIds) {
    for (Entry<String, Map<Long, Object>> valueEntry : values.entrySet()) {
        Set<Long> activeValueRowIds = Sets.intersection(valueEntry.getValue().keySet(), rowIds);
        if (!activeValueRowIds.isEmpty()) {
            Map<Long, Object> newValues = Maps.filterKeys(valueEntry.getValue(),
                    rowId -> activeValueRowIds.contains(rowId));

            logger.trace("Sending out values for {}, rowIds (limit) {}", valueEntry.getKey(),
                    Iterables.limit(activeValueRowIds, 100));

            forEachOutputConsumerOfType(ColumnValueConsumer.class,
                    c -> c.consume(valueEntry.getKey(), newValues));
        }
    }
}

From source file:org.apache.rya.indexing.accumulo.entity.StarQuery.java

public static StarQuery getConstrainedStarQuery(final StarQuery query, final BindingSet bs) {

    if (bs.size() == 0) {
        return query;
    }//from  w  w w  .j a  va2s.c om

    final Set<String> bindingNames = bs.getBindingNames();
    final Set<String> unCommonVarNames = query.getUnCommonVars();
    final Set<String> intersectVar = Sets.intersection(bindingNames, unCommonVarNames);

    if (!query.commonVarConstant()) {

        final Value v = bs.getValue(query.getCommonVarName());

        if (v != null) {
            query.commonVar.setValue(v);
        }
    }

    for (final String s : intersectVar) {
        try {
            query.nodeColumnCond[query.varPos.get(s)] = query
                    .setValue(query.nodeColumnCond[query.varPos.get(s)], bs.getValue(s));
        } catch (final RyaTypeResolverException e) {
            e.printStackTrace();
        }
    }

    return query;
}

From source file:com.facebook.buck.apple.AppleTestDescription.java

@Override
public <A extends Arg> BuildRule createBuildRule(TargetGraph targetGraph, BuildRuleParams params,
        BuildRuleResolver resolver, A args) throws NoSuchBuildTargetException {
    AppleDebugFormat debugFormat = AppleDebugFormat.FLAVOR_DOMAIN.getValue(params.getBuildTarget())
            .orElse(appleConfig.getDefaultDebugInfoFormatForTests());
    if (params.getBuildTarget().getFlavors().contains(debugFormat.getFlavor())) {
        params = params.withoutFlavor(debugFormat.getFlavor());
    }//  w ww  .  j a v  a  2  s.  c  o  m

    boolean createBundle = Sets.intersection(params.getBuildTarget().getFlavors(), AUXILIARY_LIBRARY_FLAVORS)
            .isEmpty();
    // Flavors pertaining to the library targets that are generated.
    Sets.SetView<Flavor> libraryFlavors = Sets.difference(params.getBuildTarget().getFlavors(),
            AUXILIARY_LIBRARY_FLAVORS);
    boolean addDefaultPlatform = libraryFlavors.isEmpty();
    ImmutableSet.Builder<Flavor> extraFlavorsBuilder = ImmutableSet.builder();
    if (createBundle) {
        extraFlavorsBuilder.add(LIBRARY_FLAVOR, CxxDescriptionEnhancer.MACH_O_BUNDLE_FLAVOR);
    }
    extraFlavorsBuilder.add(debugFormat.getFlavor());
    if (addDefaultPlatform) {
        extraFlavorsBuilder.add(defaultCxxPlatform.getFlavor());
    }

    Optional<MultiarchFileInfo> multiarchFileInfo = MultiarchFileInfos.create(appleCxxPlatformFlavorDomain,
            params.getBuildTarget());
    AppleCxxPlatform appleCxxPlatform;
    ImmutableList<CxxPlatform> cxxPlatforms;
    if (multiarchFileInfo.isPresent()) {
        ImmutableList.Builder<CxxPlatform> cxxPlatformBuilder = ImmutableList.builder();
        for (BuildTarget thinTarget : multiarchFileInfo.get().getThinTargets()) {
            cxxPlatformBuilder.add(cxxPlatformFlavorDomain.getValue(thinTarget).get());
        }
        cxxPlatforms = cxxPlatformBuilder.build();
        appleCxxPlatform = multiarchFileInfo.get().getRepresentativePlatform();
    } else {
        CxxPlatform cxxPlatform = cxxPlatformFlavorDomain.getValue(params.getBuildTarget())
                .orElse(defaultCxxPlatform);
        cxxPlatforms = ImmutableList.of(cxxPlatform);
        try {
            appleCxxPlatform = appleCxxPlatformFlavorDomain.getValue(cxxPlatform.getFlavor());
        } catch (FlavorDomainException e) {
            throw new HumanReadableException(e, "%s: Apple test requires an Apple platform, found '%s'",
                    params.getBuildTarget(), cxxPlatform.getFlavor().getName());
        }
    }

    Optional<TestHostInfo> testHostInfo;
    if (args.testHostApp.isPresent()) {
        testHostInfo = Optional.of(createTestHostInfo(params, resolver, args.testHostApp.get(), debugFormat,
                libraryFlavors, cxxPlatforms));
    } else {
        testHostInfo = Optional.empty();
    }

    BuildTarget libraryTarget = params.getBuildTarget().withAppendedFlavors(extraFlavorsBuilder.build())
            .withAppendedFlavors(debugFormat.getFlavor())
            .withAppendedFlavors(LinkerMapMode.NO_LINKER_MAP.getFlavor());
    BuildRule library = createTestLibraryRule(targetGraph, params, resolver, args,
            testHostInfo.map(TestHostInfo::getTestHostAppBinarySourcePath),
            testHostInfo.map(TestHostInfo::getBlacklist).orElse(ImmutableSet.of()), libraryTarget);
    if (!createBundle || SwiftLibraryDescription.isSwiftTarget(libraryTarget)) {
        return library;
    }

    SourcePathResolver sourcePathResolver = new SourcePathResolver(new SourcePathRuleFinder(resolver));
    String platformName = appleCxxPlatform.getAppleSdk().getApplePlatform().getName();

    BuildRule bundle = AppleDescriptions.createAppleBundle(cxxPlatformFlavorDomain, defaultCxxPlatform,
            appleCxxPlatformFlavorDomain, targetGraph,
            params.copyWithChanges(
                    params.getBuildTarget().withAppendedFlavors(BUNDLE_FLAVOR, debugFormat.getFlavor(),
                            LinkerMapMode.NO_LINKER_MAP.getFlavor(),
                            AppleDescriptions.NO_INCLUDE_FRAMEWORKS_FLAVOR),
                    // We have to add back the original deps here, since they're likely
                    // stripped from the library link above (it doesn't actually depend on them).
                    Suppliers.ofInstance(ImmutableSortedSet.<BuildRule>naturalOrder().add(library)
                            .addAll(params.getDeclaredDeps().get()).build()),
                    params.getExtraDeps()),
            resolver, codeSignIdentityStore, provisioningProfileStore, library.getBuildTarget(),
            args.getExtension(), Optional.empty(), args.infoPlist, args.infoPlistSubstitutions, args.deps,
            args.tests, debugFormat, appleConfig.useDryRunCodeSigning(), appleConfig.cacheBundlesAndPackages());
    resolver.addToIndex(bundle);

    Optional<SourcePath> xctool = getXctool(params, resolver, sourcePathResolver);

    return new AppleTest(xctool, appleConfig.getXctoolStutterTimeoutMs(), appleCxxPlatform.getXctest(),
            appleConfig.getXctestPlatformNames().contains(platformName), platformName,
            appleConfig.getXctoolDefaultDestinationSpecifier(), Optional.of(args.destinationSpecifier),
            params.copyWithDeps(Suppliers.ofInstance(ImmutableSortedSet.of(bundle)),
                    Suppliers.ofInstance(ImmutableSortedSet.of())),
            sourcePathResolver, bundle, testHostInfo.map(TestHostInfo::getTestHostApp), args.contacts,
            args.labels, args.getRunTestSeparately(), xcodeDeveloperDirectorySupplier,
            appleConfig.getTestLogDirectoryEnvironmentVariable(),
            appleConfig.getTestLogLevelEnvironmentVariable(), appleConfig.getTestLogLevel(),
            args.testRuleTimeoutMs.map(Optional::of).orElse(defaultTestRuleTimeoutMs), args.isUiTest(),
            args.snapshotReferenceImagesPath);
}