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

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

Introduction

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

Prototype

public static <K, V> SortedMapDifference<K, V> difference(SortedMap<K, ? extends V> left,
        Map<? extends K, ? extends V> right) 

Source Link

Document

Computes the difference between two sorted maps, using the comparator of the left map, or Ordering.natural() if the left map uses the natural ordering of its elements.

Usage

From source file:additionalpipes.inventory.components.PropertyMap.java

@Override
public void writeData(DataOutputStream data) throws IOException {
    MapDifference<Property, Property> diff = Maps.difference(prevValue, value);

    Map<Property, ValueDifference<Property>> changed = diff.entriesDiffering();
    Map<Property, Property> added = diff.entriesOnlyOnRight();
    Map<Property, Property> removed = diff.entriesOnlyOnLeft();
    data.writeInt(changed.size() + added.size() + removed.size());

    for (Entry<Property, ValueDifference<Property>> e : changed.entrySet()) {
        data.writeBoolean(false);/*from www . ja  v  a 2  s.c om*/
        Property.writePacket(e.getKey(), data);
        Property.writePacket(e.getValue().rightValue(), data);
    }
    for (Entry<Property, Property> e : added.entrySet()) {
        data.writeBoolean(false);
        Property.writePacket(e.getKey(), data);
        Property.writePacket(e.getValue(), data);
    }
    for (Entry<Property, Property> e : removed.entrySet()) {
        data.writeBoolean(true);
        Property.writePacket(e.getKey(), data);
    }

    prevValue = ImmutableMap.copyOf(value);
}

From source file:be.solidx.hot.shows.AbstractWebSocket.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<Options, Handler<CLOSURE>> refreshSocket(WebSocket<CLOSURE, MAP> updatedWebSocket) {
    MapDifference<Options, Handler<CLOSURE>> diff = Maps.difference(socketHandlerAdapterMap,
            updatedWebSocket.getSocketHandlerAdapterMap());
    for (Entry<Options, ValueDifference<Handler<CLOSURE>>> differingEntry : diff.entriesDiffering()
            .entrySet()) {//from w  ww . j a  v a2  s  .  c  o  m
        AbstractWebSocketHandler<CLOSURE> newHandler = (AbstractWebSocketHandler) differingEntry.getValue()
                .rightValue();
        AbstractWebSocketHandler<CLOSURE> currentHandler = (AbstractWebSocketHandler) differingEntry.getValue()
                .leftValue();
        currentHandler.getSocketHandlerAdapter().updateClosures(newHandler.socketHandlerAdapter.connectClosure,
                newHandler.socketHandlerAdapter.abstractConnection.messageClosure,
                newHandler.socketHandlerAdapter.abstractConnection.closeClosure);
    }
    for (Entry<Options, Handler<CLOSURE>> entry : diff.entriesOnlyOnLeft().entrySet()) {
        AbstractWebSocketHandler<CLOSURE> currentHandler = (AbstractWebSocketHandler) entry.getValue();
        currentHandler.closed = true;
    }
    socketHandlerAdapterMap.putAll(diff.entriesOnlyOnRight());
    return diff.entriesOnlyOnRight();
}

From source file:org.apache.fluo.recipes.core.map.it.DocumentObserver.java

private static Map<String, Long> calculateChanges(Map<String, Long> newCounts, Map<String, Long> currCounts) {
    Map<String, Long> changes = new HashMap<>();

    // guava Maps class
    MapDifference<String, Long> diffs = Maps.difference(currCounts, newCounts);

    // compute the diffs for words that changed
    changes.putAll(//from w  w  w  .j  a  v a2s.  com
            Maps.transformValues(diffs.entriesDiffering(), vDiff -> vDiff.rightValue() - vDiff.leftValue()));

    // add all new words
    changes.putAll(diffs.entriesOnlyOnRight());

    // subtract all words no longer present
    changes.putAll(Maps.transformValues(diffs.entriesOnlyOnLeft(), l -> l * -1));

    return changes;
}

From source file:io.fabric8.process.manager.support.ApplyConfigurationTask.java

@Override
public void install(InstallContext installContext, ProcessConfig config, String id, File installDir)
        throws Exception {
    Map<String, String> templates = Maps.filterKeys(configuration, isTemplate);
    Map<String, String> plainFiles = Maps.difference(configuration, templates).entriesOnlyOnLeft();
    ProcessManagerService.substituteEnvironmentVariableExpressions((Map) variables, config.getEnvironment());
    Map<String, String> renderedTemplates = Maps.transformValues(templates,
            new MvelTemplateRendering(variables));
    File baseDir = ProcessUtils.findInstallDir(installDir);
    applyTemplates(installContext, renderedTemplates, baseDir);
    applyPlainConfiguration(installContext, plainFiles, baseDir);

}

From source file:com.cloudera.nav.sdk.model.entities.UDPChangeSet.java

/**
 * Add specified properties to properties to be added
 * @param properties//w w  w.  ja v  a  2s. c om
 */
public void addProperties(Map<String, String> properties) {
    if (MapUtils.isNotEmpty(properties)) {
        newProperties.putAll(properties);
        removeProperties.removeAll(properties.keySet());
        if (overrideProperties != null) {
            overrideProperties = Maps
                    .newHashMap(Maps.difference(overrideProperties, properties).entriesOnlyOnLeft());
        }
    }
}

From source file:org.apache.cassandra.schema.Keyspaces.java

MapDifference<String, KeyspaceMetadata> diff(Keyspaces other) {
    return Maps.difference(keyspaces, other.keyspaces);
}

From source file:io.fabric8.docker.provider.customizer.ApplyConfigurationStep.java

public void install() throws Exception {
    Map<String, String> templates = Maps.filterKeys(configuration, isTemplate);
    Map<String, String> plainFiles = Maps.difference(configuration, templates).entriesOnlyOnLeft();
    Map<String, String> renderedTemplates = Maps.transformValues(templates,
            new MvelTemplateRendering(variables));

    applyTemplates(renderedTemplates, baseDir);
    applyPlainConfiguration(plainFiles, baseDir);
}

From source file:models.DeploymentDiff.java

/**
 * Computes the changes from one manifest to another.
 *
 * @param oldManifest the old manifest/*ww w.j a  v a  2 s  . c o m*/
 * @param newManifest the new manifest
 * @return a list of package changes
 */
List<PackageChange> getPackageChanges(final Manifest oldManifest, final Manifest newManifest) {
    final List<PackageVersion> oldPackages = oldManifest.getPackages();
    final ImmutableMap<String, PackageVersion> oldMap = Maps.uniqueIndex(oldPackages,
            (v) -> v.getPkg().getName());
    final ImmutableMap<String, PackageVersion> newMap = Maps.uniqueIndex(newManifest.getPackages(),
            (v) -> v.getPkg().getName());
    final MapDifference<String, PackageVersion> mapDifference = Maps.difference(oldMap, newMap);

    final List<PackageChange> changes = Lists.newArrayList();
    mapDifference.entriesOnlyOnLeft().forEach(
            (k, v) -> changes.add(new PackageChange(k, Optional.of(v.getVersion()), Optional.empty())));

    mapDifference.entriesOnlyOnRight().forEach(
            (k, v) -> changes.add(new PackageChange(k, Optional.empty(), Optional.of(v.getVersion()))));

    mapDifference.entriesDiffering().forEach((k, v) -> changes.add(new PackageChange(k,
            Optional.of(v.leftValue().getVersion()), Optional.of(v.rightValue().getVersion()))));

    mapDifference.entriesInCommon().forEach((k, v) -> changes
            .add(new PackageChange(k, Optional.of(v.getVersion()), Optional.of(v.getVersion()))));
    changes.sort(Comparator.comparing(PackageChange::getName));
    return changes;
}

From source file:co.cask.cdap.internal.app.deploy.pipeline.CreateSchedulesStage.java

@Override
public void process(ApplicationWithPrograms input) throws Exception {
    ApplicationSpecification existingAppSpec = input.getExistingAppSpecification();
    Map<String, ScheduleSpecification> existingSchedulesMap;
    if (existingAppSpec == null) {
        existingSchedulesMap = ImmutableMap.of();
    } else {/*  www.j a  va 2  s  . c  om*/
        existingSchedulesMap = existingAppSpec.getSchedules();
    }

    MapDifference<String, ScheduleSpecification> mapDiff = Maps.difference(existingSchedulesMap,
            input.getSpecification().getSchedules());
    for (Map.Entry<String, ScheduleSpecification> entry : mapDiff.entriesOnlyOnLeft().entrySet()) {
        // delete schedules that existed in the old app spec, but don't anymore
        ScheduleSpecification scheduleSpec = entry.getValue();
        ProgramType programType = ProgramType
                .valueOfSchedulableType(scheduleSpec.getProgram().getProgramType());
        scheduler.deleteSchedule(
                Id.Program.from(input.getId(), programType, scheduleSpec.getProgram().getProgramName()),
                scheduleSpec.getProgram().getProgramType(), scheduleSpec.getSchedule().getName());
    }

    for (Map.Entry<String, MapDifference.ValueDifference<ScheduleSpecification>> entry : mapDiff
            .entriesDiffering().entrySet()) {
        // Update those schedules - the new schedules have the same IDs but different specs
        ScheduleSpecification newScheduleSpec = entry.getValue().rightValue();
        ScheduleSpecification oldScheduleSpec = entry.getValue().leftValue();
        if (newScheduleSpec.getSchedule().equals(oldScheduleSpec.getSchedule())) {
            // The schedules are exactly the same - the difference in spec might come from the properties map -
            // hence it is useless to update the schedule
            continue;
        }

        ProgramType programType = ProgramType
                .valueOfSchedulableType(newScheduleSpec.getProgram().getProgramType());
        scheduler.updateSchedule(
                Id.Program.from(input.getId(), programType, newScheduleSpec.getProgram().getProgramName()),
                newScheduleSpec.getProgram().getProgramType(), newScheduleSpec.getSchedule());
    }

    for (Map.Entry<String, ScheduleSpecification> entry : mapDiff.entriesOnlyOnRight().entrySet()) {
        ScheduleSpecification scheduleSpec = entry.getValue();
        ProgramType programType = ProgramType
                .valueOfSchedulableType(scheduleSpec.getProgram().getProgramType());
        scheduler.schedule(
                Id.Program.from(input.getId(), programType, scheduleSpec.getProgram().getProgramName()),
                scheduleSpec.getProgram().getProgramType(), scheduleSpec.getSchedule());
    }

    // Note: the mapDiff also has a entriesInCommon method returning all entries in left and right maps
    // which have exactly the same keys and values. In that case, we don't need to do anything, not
    // even to update the schedule

    // Emit the input to next stage.
    emit(input);
}

From source file:components.cells.Cells.java

private static <T> Map<IPosition, T> merge(final T initialSymbol, final Map<IPosition, T> left,
        final Map<IPosition, T> right) {
    final Builder<IPosition, T> builder = new ImmutableSortedMap.Builder<IPosition, T>(Ordering.natural());
    final MapDifference<IPosition, T> difference = Maps.difference(left, right);
    for (final Entry<IPosition, T> mutation : difference.entriesInCommon().entrySet())
        if (!mutation.getValue().equals(initialSymbol))
            builder.put(mutation);/*w  w w .  j  a  va 2 s  . c  o  m*/
    for (final Entry<IPosition, T> mutation : difference.entriesOnlyOnLeft().entrySet())
        if (!mutation.getValue().equals(initialSymbol))
            builder.put(mutation);
    for (final Entry<IPosition, T> mutation : difference.entriesOnlyOnRight().entrySet())
        if (!mutation.getValue().equals(initialSymbol))
            builder.put(mutation);
    for (final Entry<IPosition, ValueDifference<T>> mutation : difference.entriesDiffering().entrySet()) {
        final T rightValue = mutation.getValue().rightValue();
        if (!rightValue.equals(initialSymbol))
            builder.put(mutation.getKey(), rightValue);
    }
    return builder.build();
}