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:com.streamsets.pipeline.sdk.StageRunner.java

@SuppressWarnings("unchecked")
private void configureStage(S stage, Map<String, Object> configuration) {
    try {//from w  w w. j  a  v a  2s.  c om
        Set<String> fields = getStageConfigurationFields(stage.getClass());
        Set<String> configs = configuration.keySet();
        if (!fields.equals(configs)) {
            Set<String> missingConfigs = Sets.difference(fields, configs);
            Set<String> extraConfigs = Sets.difference(configs, fields);

            missingConfigs = filterNonActiveConfigurationsFromMissing(stage, configuration, missingConfigs);
            if (missingConfigs.size() + extraConfigs.size() > 0) { //x
                throw new RuntimeException(Utils.format(
                        "Invalid stage configuration for '{}', Missing configurations '{}' and invalid configurations '{}'",
                        stage.getClass().getName(), missingConfigs, extraConfigs));
            }
        }
        for (Field field : stage.getClass().getFields()) {
            if (field.isAnnotationPresent(ConfigDef.class)) {
                ConfigDef configDef = field.getAnnotation(ConfigDef.class);
                if (isConfigurationActive(configDef, configuration)) {
                    if (configDef.type() != ConfigDef.Type.MAP) {
                        field.set(stage, configuration.get(field.getName()));
                    } else {
                        //we need to handle special case of List of Map elements with key/value entries
                        Object value = configuration.get(field.getName());
                        if (value != null && value instanceof List) {
                            Map map = new HashMap();
                            for (Map element : (List<Map>) value) {
                                if (!element.containsKey("key") || !element.containsKey("value")) {
                                    throw new RuntimeException(Utils.format(
                                            "Invalid stage configuration for '{}' Map as list must have"
                                                    + " a List of Maps all with 'key' and 'value' entries",
                                            field.getName()));
                                }
                                String k = (String) element.get("key");
                                String v = (String) element.get("value");
                                map.put(k, v);
                            }
                            value = map;
                        }
                        field.set(stage, value);
                    }
                }
            }
        }
    } catch (Exception ex) {
        if (ex instanceof RuntimeException) {
            throw (RuntimeException) ex;
        }
        throw new RuntimeException(ex);
    }
}

From source file:org.caleydo.view.domino.internal.data.Numerical2DDataDomainValues.java

private TypedGroupSet resolve(Set<Integer> invalid, TypedSet d) {
    if (invalid.isEmpty())
        return TypedGroupSet.createUngrouped(d);

    TypedSetGroup normal = new TypedSetGroup(
            new TypedSet(ImmutableSet.copyOf(Sets.difference(d, invalid)), d.getIdType()), "Normal",
            getDataDomain().getColor());
    TypedSetGroup invalidG = new TypedSetGroup(new TypedSet(ImmutableSet.copyOf(invalid), d.getIdType()), "NaN",
            Color.NOT_A_NUMBER_COLOR);
    return new TypedGroupSet(normal, invalidG);
}

From source file:org.dishevelled.venn.model.QuaternaryVennModelImpl.java

/**
 * Create a new quaternary venn model with the specified sets.
 *
 * @param first first set, must not be null
 * @param second second set, must not be null
 * @param third third set, must not be null
 * @param fourth fourth set, must not be null
 *///w  w w . j ava 2  s  .c  o  m
public QuaternaryVennModelImpl(final Set<? extends E> first, final Set<? extends E> second,
        final Set<? extends E> third, final Set<? extends E> fourth) {
    if (first == null) {
        throw new IllegalArgumentException("first must not be null");
    }
    if (second == null) {
        throw new IllegalArgumentException("second must not be null");
    }
    if (third == null) {
        throw new IllegalArgumentException("third must not be null");
    }
    if (fourth == null) {
        throw new IllegalArgumentException("fourth must not be null");
    }

    // todo  defensive copy?
    this.first = new ObservableSetImpl(first);
    this.second = new ObservableSetImpl(second);
    this.third = new ObservableSetImpl(third);
    this.fourth = new ObservableSetImpl(fourth);

    // alias
    ObservableSet<E> f = this.first;
    ObservableSet<E> s = this.second;
    ObservableSet<E> t = this.third;
    ObservableSet<E> r = this.fourth;
    firstOnly = Sets.difference(Sets.difference(Sets.difference(f, s), t), r); // f - s - t - r
    secondOnly = Sets.difference(Sets.difference(Sets.difference(s, f), t), r); // s - f - t - r
    thirdOnly = Sets.difference(Sets.difference(Sets.difference(t, f), s), r); // t - f - s - r
    fourthOnly = Sets.difference(Sets.difference(Sets.difference(r, f), s), t); // r - f - s - t
    firstSecond = Sets.difference(Sets.difference(Sets.intersection(f, s), t), r); // f n s - t - r
    firstThird = Sets.difference(Sets.difference(Sets.intersection(f, t), s), r); // f n t - s - r
    firstFourth = Sets.difference(Sets.difference(Sets.intersection(f, r), s), t); // f n r - s - t
    secondThird = Sets.difference(Sets.difference(Sets.intersection(s, t), f), r); // s n t - f - r
    secondFourth = Sets.difference(Sets.difference(Sets.intersection(s, r), f), t); // s n r - f - t
    thirdFourth = Sets.difference(Sets.difference(Sets.intersection(t, r), f), s); // t n r - f - s
    firstSecondThird = Sets.difference(Sets.intersection(f, Sets.intersection(s, t)), r); // f n s n t - r
    firstSecondFourth = Sets.difference(Sets.intersection(f, Sets.intersection(s, r)), t); // f n s n r - t
    firstThirdFourth = Sets.difference(Sets.intersection(f, Sets.intersection(t, r)), s); // f n t n r - s
    secondThirdFourth = Sets.difference(Sets.intersection(s, Sets.intersection(t, r)), f); // s n t n r - f
    intersection = Sets.intersection(f, Sets.intersection(s, Sets.intersection(t, r))); // f n s n t n r
    union = Sets.union(f, Sets.union(s, Sets.union(t, r))); // f u s u t u r
    selection = new SelectionView<E>(union, f, s, t, r);

    exclusives = new HashMap<ImmutableBitSet, Set<E>>(15);

    exclusives.put(toImmutableBitSet(0), firstOnly);
    exclusives.put(toImmutableBitSet(1), secondOnly);
    exclusives.put(toImmutableBitSet(2), thirdOnly);
    exclusives.put(toImmutableBitSet(3), fourthOnly);

    exclusives.put(toImmutableBitSet(0, 1), firstSecond);
    exclusives.put(toImmutableBitSet(0, 2), firstThird);
    exclusives.put(toImmutableBitSet(0, 3), firstFourth);
    exclusives.put(toImmutableBitSet(1, 2), secondThird);
    exclusives.put(toImmutableBitSet(1, 3), secondFourth);
    exclusives.put(toImmutableBitSet(2, 3), thirdFourth);

    exclusives.put(toImmutableBitSet(0, 1, 2), firstSecondThird);
    exclusives.put(toImmutableBitSet(0, 1, 3), firstSecondFourth);
    exclusives.put(toImmutableBitSet(0, 2, 3), firstThirdFourth);
    exclusives.put(toImmutableBitSet(1, 2, 3), secondThirdFourth);

    exclusives.put(toImmutableBitSet(0, 1, 2, 3), intersection);
}

From source file:de.iteratec.iteraplan.presentation.dialog.InformationSystemInterface.model.TransportAssociationComponentModel.java

@Override
protected void setConnectedElements(InformationSystemInterface target, Set<Transport> toConnect) {
    final Set<Transport> existingTransports = Sets.newHashSet();
    final Set<Transport> newTransports = Sets.newHashSet();
    for (Transport transport : toConnect) {
        Transport existingTransport = lookUpConnectedTransportByBusinessObject(target.getTransports(),
                transport.getBusinessObject());
        if (existingTransport != null) {
            existingTransport.setDirection(transport.getDirection());
            existingTransports.add(existingTransport);
        } else {/*from  w w  w.  j a  v a  2s  . c  o m*/
            newTransports.add(transport);
        }
    }

    //delete 
    ImmutableSet<Transport> deletedTransports = Sets.difference(target.getTransports(), existingTransports)
            .immutableCopy();
    target.getTransports().removeAll(deletedTransports);

    //add new
    for (Transport transport : newTransports) {
        Transport newTransport = BuildingBlockFactory.createTransport();
        newTransport.setDirection(transport.getDirection());

        BusinessObject businessObject = SpringServiceFactory.getBusinessObjectService()
                .loadObjectById(transport.getBusinessObject().getId());
        newTransport.addBusinessObject(businessObject);

        target.addTransport(newTransport);
    }
}

From source file:org.obiba.mica.core.service.SchemaFormContentFileService.java

private Iterable<Object> saveAndDeleteFiles(JSONArray oldFiles, JSONArray newFiles, String entityPath) {
    cleanFileJsonArrays(oldFiles, newFiles);
    Iterable<Object> toDelete = Sets.difference(Sets.newHashSet(oldFiles), Sets.newHashSet(newFiles));
    Iterable<Object> toSave = Sets.difference(Sets.newHashSet(newFiles), Sets.newHashSet(oldFiles));

    toDelete.forEach(file -> fileStoreService.delete(((LinkedHashMap) file).get("id").toString()));
    saveFiles(toSave, entityPath);//  w  w  w .  j  av  a  2s  .c  o m
    return toDelete;
}

From source file:org.onosproject.store.consistent.impl.DefaultAsyncDistributedSet.java

@Override
public CompletableFuture<Boolean> retainAll(Collection<? extends E> c) {
    final MeteringAgent.Context timer = monitor.startTimer(RETAIN_ALL);
    return backingMap.keySet().thenApply(set -> Sets.difference(set, Sets.newHashSet(c)))
            .thenCompose(this::removeAll).whenComplete((r, e) -> timer.stop(null));
}

From source file:com.continuuity.loom.layout.NodeLayoutGenerator.java

/**
 * Get an ordered list of possible {@link NodeLayout}s to use in the cluster. If earlier a node layout appears in the
 * list, the more preferred it is. Only one {@link NodeLayout} per valid service set will be returned.
 *
 * @return List of node layouts that can be used in the cluster, ordered by preference.
 *///from   ww  w .  ja  v  a  2  s .com
public List<NodeLayout> generateNodeLayoutPreferences() {
    long start = System.nanoTime();
    // heuristic: if we need to place some services on the cluster, and these services have
    // no constraints, place them everywhere on the cluster.  This can significantly shrink the search space.
    Set<String> unconstrainedServices = findUnconstrainedServices();

    // get valid service sets of clusterServices that have constraints
    Set<String> constrainedServices = Sets.difference(clusterServices, unconstrainedServices);
    Set<Set<String>> validServiceSets = findValidServiceSets(Sets.newHashSet(constrainedServices));

    // add unconstrained clusterServices to each valid service set.
    if (!unconstrainedServices.isEmpty()) {
        for (Set<String> validServiceSet : validServiceSets) {
            validServiceSet.addAll(unconstrainedServices);
        }
        validServiceSets.add(unconstrainedServices);
    }
    long dur = (System.nanoTime() - start) / 1000000;
    LOG.debug("took {} ms to find {} valid service sets", dur, validServiceSets.size());

    start = System.nanoTime();
    Set<NodeLayout> validNodeLayouts = findValidNodeLayouts(validServiceSets);
    dur = (System.nanoTime() - start) / 1000000;
    LOG.debug("took {} ms to find {} valid node layouts", dur, validNodeLayouts.size());

    // We need to deterministically choose the same cluster.  Nodelayouts earlier in the traversal order are
    // preferred.
    start = System.nanoTime();
    List<NodeLayout> traversalOrder = narrowNodeLayouts(validNodeLayouts, null, null);
    dur = (System.nanoTime() - start) / 1000000;
    LOG.debug("took {} ms to narrow to {} valid node layouts", dur, traversalOrder.size());

    return traversalOrder;
}

From source file:com.github.fge.jsonpatch.diff.JsonDiff.java

private static void generateObjectDiffs(final DiffProcessor processor, final JsonPointer pointer,
        final ObjectNode source, final ObjectNode target) {
    final Set<String> firstFields = Sets.newTreeSet(Sets.newHashSet(source.fieldNames()));
    final Set<String> secondFields = Sets.newTreeSet(Sets.newHashSet(target.fieldNames()));

    for (final String field : Sets.difference(firstFields, secondFields))
        processor.valueRemoved(pointer.append(field), source.get(field));

    for (final String field : Sets.difference(secondFields, firstFields))
        processor.valueAdded(pointer.append(field), target.get(field));

    for (final String field : Sets.intersection(firstFields, secondFields))
        generateDiffs(processor, pointer.append(field), source.get(field), target.get(field));
}

From source file:org.apache.crunch.impl.mr.plan.Edge.java

public Map<NodePath, PCollectionImpl> getSplitPoints(boolean breakpointsOnly) {
    List<NodePath> np = Lists.newArrayList(paths);
    List<PCollectionImpl<?>> smallestOverallPerPath = Lists.newArrayListWithExpectedSize(np.size());
    Map<PCollectionImpl<?>, Set<Integer>> pathCounts = Maps.newTreeMap(PCOL_CMP);
    Map<NodePath, PCollectionImpl> splitPoints = Maps.newHashMap();
    for (int i = 0; i < np.size(); i++) {
        long bestSize = Long.MAX_VALUE;
        boolean breakpoint = false;
        PCollectionImpl<?> best = null;
        for (PCollectionImpl<?> pc : np.get(i)) {
            if (!(pc instanceof BaseGroupedTable) && (!breakpointsOnly || pc.isBreakpoint())) {
                if (pc.isBreakpoint()) {
                    if (!breakpoint || pc.getSize() < bestSize) {
                        best = pc;/*from  w  w w  . j av a2 s  . c o m*/
                        bestSize = pc.getSize();
                        breakpoint = true;
                    }
                } else if (!breakpoint && pc.getSize() < bestSize) {
                    best = pc;
                    bestSize = pc.getSize();
                }
                Set<Integer> cnts = pathCounts.get(pc);
                if (cnts == null) {
                    cnts = Sets.newHashSet();
                    pathCounts.put(pc, cnts);
                }
                cnts.add(i);
            }
        }
        smallestOverallPerPath.add(best);
        if (breakpoint) {
            splitPoints.put(np.get(i), best);
        }
    }

    Set<Integer> missing = Sets.newHashSet();
    for (int i = 0; i < np.size(); i++) {
        if (!splitPoints.containsKey(np.get(i))) {
            missing.add(i);
        }
    }

    if (breakpointsOnly && missing.size() > 0) {
        // We can't create new splits in this mode
        return ImmutableMap.of();
    } else if (missing.isEmpty()) {
        return splitPoints;
    } else {
        // Need to either choose the smallest collection from each missing path,
        // or the smallest single collection that is on all paths as the split target.
        Set<PCollectionImpl<?>> smallest = Sets.newHashSet();
        long smallestSize = 0;
        for (Integer id : missing) {
            PCollectionImpl<?> s = smallestOverallPerPath.get(id);
            if (!smallest.contains(s)) {
                smallest.add(s);
                smallestSize += s.getSize();
            }
        }

        PCollectionImpl<?> singleBest = null;
        long singleSmallestSize = Long.MAX_VALUE;
        for (Map.Entry<PCollectionImpl<?>, Set<Integer>> e : pathCounts.entrySet()) {
            if (Sets.difference(missing, e.getValue()).isEmpty() && e.getKey().getSize() < singleSmallestSize) {
                singleBest = e.getKey();
                singleSmallestSize = singleBest.getSize();
            }
        }

        if (smallestSize < singleSmallestSize) {
            for (Integer id : missing) {
                splitPoints.put(np.get(id), smallestOverallPerPath.get(id));
            }
        } else {
            for (Integer id : missing) {
                splitPoints.put(np.get(id), singleBest);
            }
        }
    }
    return splitPoints;
}

From source file:org.caleydo.view.domino.api.model.typed.TypedGroups.java

/**
 * @param a/*w ww  .  ja  va2 s  .c  o  m*/
 * @param b
 * @return
 */
public static TypedGroupSet difference(ITypedGroupCollection a, TypedGroupList b) {
    TypedGroupSet base = a.asSet();
    IIDTypeMapper<Integer, Integer> mapper = MappingCaches.findMapper(b.getIdType(), a.getIdType());
    if (mapper == null)
        return base;

    Set<Integer> others = mapper.apply(b);
    List<TypedSetGroup> groups = new ArrayList<>(base.getGroups());

    for (TypedSetGroup g : base.getGroups()) {
        Set<Integer> ids = ImmutableSet.copyOf(Sets.difference(g, others));
        if (ids.isEmpty())
            continue;
        groups.add(new TypedSetGroup(ids, a.getIdType(), g.getLabel(), g.getColor()));
    }
    return asSet(groups, a.getIdType());
}