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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the difference of two sets.

Usage

From source file:org.onosproject.store.resource.impl.EncodableDiscreteResources.java

@Override
public DiscreteResources difference(DiscreteResources other) {
    if (other instanceof EncodableDiscreteResources) {
        EncodableDiscreteResources cast = (EncodableDiscreteResources) other;

        Map<Class<?>, EncodedDiscreteResources> newMap = new LinkedHashMap<>();
        for (Entry<Class<?>, EncodedDiscreteResources> e : this.map.entrySet()) {
            Class<?> key = e.getKey();
            EncodedDiscreteResources thisValues = e.getValue();
            EncodedDiscreteResources otherValues = cast.map.get(key);
            if (otherValues == null) {
                newMap.put(key, thisValues);
                continue;
            }/* w  w  w. j  ava 2s .c  om*/
            EncodedDiscreteResources diff = thisValues.difference(otherValues);
            // omit empty resources from a new resource set
            // empty EncodedDiscreteResources can't deserialize due to
            // inability to reproduce a Class<?> instance from the serialized data
            if (diff.isEmpty()) {
                continue;
            }
            newMap.put(key, diff);
        }

        return of(parent, newMap);
    } else if (other instanceof EmptyDiscreteResources) {
        return this;
    }

    return DiscreteResources.of(Sets.difference(values(), other.values()));
}

From source file:io.prestosql.operator.DriverFactory.java

public synchronized void noMoreDrivers() {
    if (closed) {
        return;//from   w ww  .j  ava2  s . c om
    }
    if (encounteredLifespans.size() != closedLifespans.size()) {
        Sets.difference(encounteredLifespans, closedLifespans).forEach(this::noMoreDrivers);
        verify(encounteredLifespans.size() == closedLifespans.size());
    }
    closed = true;
    for (OperatorFactory operatorFactory : operatorFactories) {
        operatorFactory.noMoreOperators();
    }
}

From source file:no.ssb.vtl.script.operations.FoldOperation.java

@Override
public DataStructure computeDataStructure() {

    // In its normal form, all elements should be present in a fold operation.
    // This should be picked up by the parser but we check once anyways.
    DataStructure childStructure = getChild().getDataStructure();

    checkContainsColumns(childStructure, elements);

    // All the elements should be of the same type.
    Class<?> newType = checkColumnType(childStructure, elements);

    // Cannot remove identifiers without grouping.
    checkNoIdentifiers(childStructure, elements);

    // Copy each columns that is not in elements.
    // Putting them first optimizes the fold operation.
    DataStructure.Builder structureBuilder = DataStructure.builder();
    for (String columnName : Sets.difference(childStructure.keySet(), elements)) {
        structureBuilder.put(columnName, childStructure.get(columnName));
    }//from   w  w w  .  j a v a  2  s .  com

    structureBuilder.put(dimension, Role.IDENTIFIER, String.class);
    structureBuilder.put(measure, Role.MEASURE, newType);
    DataStructure structure = structureBuilder.build();

    computeIndices(structure);

    return structure;
}

From source file:com.siemens.sw360.portal.tags.CompareProject.java

private void renderLinkedProjects(StringBuilder display) {
    if (ensureSomethingTodoAndNoNullLinkedProjects()) {
        Map<String, ProjectRelationship> oldLinkedProjects = old.getLinkedProjects();
        Map<String, ProjectRelationship> updateLinkedProjects = update.getLinkedProjects();
        Sets.SetView<String> removedProjectIds = Sets.difference(oldLinkedProjects.keySet(),
                updateLinkedProjects.keySet());
        Sets.SetView<String> addedProjectIds = Sets.difference(updateLinkedProjects.keySet(),
                oldLinkedProjects.keySet());
        Sets.SetView<String> commonProjectIds = Sets.intersection(updateLinkedProjects.keySet(),
                oldLinkedProjects.keySet());

        renderProjectLinkList(display, oldLinkedProjects, removedProjectIds, "Removed Project links");
        renderProjectLinkList(display, updateLinkedProjects, addedProjectIds, "Added Project links");
        renderProjectLinkListCompare(display, oldLinkedProjects, updateLinkedProjects, commonProjectIds);
    }/*  w  w w  . java  2s  . c  o  m*/
}

From source file:com.facebook.buck.jvm.java.coverage.ReportGenerator.java

private void createReport(IBundleCoverage bundleCoverage) throws IOException {
    Set<String> unknownFormats = Sets.difference(reportFormats, KNOWN_REPORT_FORMATS);
    if (!unknownFormats.isEmpty()) {
        throw new RuntimeException("Unable to parse formats: " + String.join(",", reportFormats));
    }/*from  w  w  w. j  ava2  s  . co  m*/

    // Create a concrete report visitors based on some supplied
    // configuration. In this case we use the defaults
    List<IReportVisitor> visitors = new ArrayList<>();
    if (reportFormats.contains("csv")) {
        reportDirectory.mkdirs();
        CSVFormatter csvFormatter = new CSVFormatter();
        visitors.add(
                csvFormatter.createVisitor(new FileOutputStream(new File(reportDirectory, "coverage.csv"))));
    }

    if (reportFormats.contains("html")) {
        HTMLFormatter htmlFormatter = new HTMLFormatter();
        visitors.add(htmlFormatter.createVisitor(new FileMultiReportOutput(reportDirectory)));
    }

    if (reportFormats.contains("xml")) {
        reportDirectory.mkdirs();
        XMLFormatter xmlFormatter = new XMLFormatter();
        visitors.add(
                xmlFormatter.createVisitor(new FileOutputStream(new File(reportDirectory, "coverage.xml"))));
    }

    IReportVisitor visitor = new MultiReportVisitor(visitors);
    // Initialize the report with all of the execution and session
    // information. At this point the report doesn't know about the
    // structure of the report being created
    visitor.visitInfo(execFileLoader.getSessionInfoStore().getInfos(),
            execFileLoader.getExecutionDataStore().getContents());

    // Populate the report structure with the bundle coverage information.
    // Call visitGroup if you need groups in your report.
    visitor.visitBundle(bundleCoverage, createSourceFileLocator());

    // Signal end of structure information to allow report to write all
    // information out
    visitor.visitEnd();
}

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);
    }/*  w w  w. j  av  a  2  s .c  o  m*/
    // 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();
}

From source file:se.kth.climate.fast.netcdfparquet.AvroSchemaGenerator.java

private static MetaInfo findBounds(NetcdfFile ncfile) {
    MetaInfo bi = new MetaInfo();
    Set<String> normalDims = new HashSet<>();
    Set<String> bndsDims = new HashSet<>();
    for (Variable v : ncfile.getVariables()) {
        if (v.getFullNameEscaped().contains("bnds")) {
            for (Dimension d : v.getDimensions()) {
                bndsDims.add(d.getFullNameEscaped());
            }/* w  ww .java  2  s .c om*/
        } else {
            for (Dimension d : v.getDimensions()) {
                normalDims.add(d.getFullNameEscaped());
            }
        }
    }
    SetView<String> boundDim = Sets.difference(bndsDims, normalDims);
    if (boundDim.isEmpty()) {
        LOG.info(
                "No bounds dimension found. Bounds Variables Dimensions are {} and normal Variable Dimensions are {}",
                bndsDims, normalDims);
        return bi;
    }
    for (String boundDimensionName : boundDim) {
        Dimension d = ncfile.findDimension(boundDimensionName);
        if (d == null) {
            throw new RuntimeException("Couldn't find dimension for " + boundDimensionName);
        }
        bi.dimensionSize.put(boundDimensionName, d.getLength());
    }
    for (Variable v : ncfile.getVariables()) {
        if (v.getFullNameEscaped().contains("bnds")) {
            for (Dimension d : v.getDimensions()) {
                if (boundDim.contains(d.getFullNameEscaped())) {
                    bi.variable2Dimension.put(v.getFullNameEscaped(), d.getFullNameEscaped());
                }
            }
        }
    }
    return bi;
}

From source file:org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.filters.impl.DifferenceFilterManager.java

/**
 * Get all {@link IDifferenceFilter} that should be used by default for next comparison.
 * /*from  w ww .ja v  a 2 s  . c om*/
 * @return A {@link Collection} of {@link IDifferenceFilter} that should be used by default for next
 *         comparison.
 */
public Set<IDifferenceFilter> getCurrentByDefaultFilters() {
    Set<IDifferenceFilter> storedFilter = getDisabledFilters();
    if (storedFilter == null) {
        return getInitialByDefaultFilters();
    }
    return Sets.difference(getAllFilters(), storedFilter);
}

From source file:org.jclouds.nodepool.internal.EagerNodePoolComputeServiceAdapter.java

@Override
public NodeWithInitialCredentials createNodeWithGroupEncodedIntoName(String group, String name,
        Template template) {/*  w  ww . ja  va  2 s. c o  m*/
    int count = 1;
    synchronized (this) {
        TemplateOptions options = template.getOptions().clone();

        // if no user is provided we set the pool's user
        if (options.getLoginUser() == null) {
            options.overrideLoginCredentials(LoginCredentials
                    .fromCredentials(checkNotNull(initialCredentialsBuilder.build().getAdminCredentials())));
        }

        logger.info(">> assigning pool node to frontend group %s", group);
        Set<NodeMetadata> backendNodes = getBackendNodes();
        checkState(!backendNodes.isEmpty());
        Set<NodeMetadata> frontendNodes = metadataStore.loadAll(backendNodes);
        checkState(frontendNodes.size() + count <= maxSize,
                "cannot add more nodes to pool [requested: %s, current: %s, max: %s]", count,
                frontendNodes.size(), maxSize);

        SetView<NodeMetadata> availableNodes = Sets.difference(backendNodes, frontendNodes);

        if (availableNodes.size() < 1) {
            if (backendNodes.size() < maxSize && backendNodes.size() + count <= maxSize) {
                logger.info(
                        ">> all pool nodes are assigned, requiring additional nodes [requested: %s, current: %s, next: %s, max: %s]",
                        count, frontendNodes.size(), frontendNodes.size() + 1, maxSize);
                addToPool(count);
                // update backend and available sets, no need to update frontend
                backendNodes = getBackendNodes();
                availableNodes = Sets.difference(backendNodes, frontendNodes);
                logger.info("<< additional nodes added to the pool and ready");
            } else {
                logger.error("maximum pool size reached (%s)", maxSize);
                throw new IllegalStateException(String.format("maximum pool size reached (%s)", maxSize));
            }
        }
        NodeMetadata userNode = Iterables.get(availableNodes, 0);
        NodeMetadata node = metadataStore.store(userNode, options, group);
        logger.info("pool node assigned");
        return new NodeWithInitialCredentials(node);
    }
}

From source file:com.siemens.sw360.portal.tags.DisplayProjectChanges.java

private void renderLinkedProjects(StringBuilder display) {
    if (ensureSomethingTodoAndNoNullLinkedProjects()) {

        Set<String> changedProjectIds = Sets.intersection(additions.getLinkedProjects().keySet(),
                deletions.getLinkedProjects().keySet());
        Set<String> linkedProjectsInDb = nullToEmptyMap(actual.getLinkedProjects()).keySet();
        //keep only projects that are still in the database
        changedProjectIds = Sets.intersection(changedProjectIds, linkedProjectsInDb);

        Set<String> removedProjectIds = Sets.difference(deletions.getLinkedProjects().keySet(),
                changedProjectIds);/*from w w  w.ja va2  s.  com*/
        removedProjectIds = Sets.intersection(removedProjectIds, linkedProjectsInDb);

        Set<String> addedProjectIds = Sets.difference(additions.getLinkedProjects().keySet(),
                changedProjectIds);

        renderProjectLinkList(display, deletions.getLinkedProjects(), removedProjectIds,
                "Removed Project Links");
        renderProjectLinkList(display, additions.getLinkedProjects(), addedProjectIds, "Added Project Links");
        renderProjectLinkListCompare(display, actual.getLinkedProjects(), deletions.getLinkedProjects(),
                additions.getLinkedProjects(), changedProjectIds);
    }
}