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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the symmetric difference of two sets.

Usage

From source file:org.onosproject.cluster.ClusterMetadataDiff.java

/**
 * Returns a mapping of all partition diffs.
 * @return partition diffs.//from w ww  . j  a v a  2s.  com
 */
public Map<PartitionId, PartitionDiff> partitionDiffs() {
    Map<PartitionId, Partition> oldPartitions = Maps.newHashMap();
    oldValue.getPartitions().forEach(p -> oldPartitions.put(p.getId(), p));
    Map<PartitionId, Partition> newPartitions = Maps.newHashMap();
    newValue.getPartitions().forEach(p -> newPartitions.put(p.getId(), p));
    checkState(Sets.symmetricDifference(oldPartitions.keySet(), newPartitions.keySet()).isEmpty(),
            "Number of partitions cannot change");
    Map<PartitionId, PartitionDiff> partitionDiffs = Maps.newHashMap();
    oldPartitions.forEach((k, v) -> {
        partitionDiffs.put(k, new PartitionDiff(v, newPartitions.get(k)));
    });
    return partitionDiffs;
}

From source file:uk.co.flax.ukmp.twitter.PartyListHandler.java

public void refreshLists() {
    Map<String, Set<Long>> memberIds = new HashMap<>();

    Authorization auth = AuthorizationFactory.getInstance(twitterConfig);
    TwitterFactory tf = new TwitterFactory(twitterConfig);
    Twitter twitter = tf.getInstance(auth);
    for (PartyConfiguration pc : parties.values()) {
        Set<Long> ids = readPartyIds(twitter, pc.getTwitterScreenName(), pc.getTwitterListSlug(),
                pc.getDisplayName());/*w ww .j  av  a  2  s  .co  m*/
        if (!ids.isEmpty()) {
            memberIds.put(pc.getDisplayName(), ids);
        }
    }

    synchronized (partyMemberIds) {
        for (String party : memberIds.keySet()) {
            if (!partyMemberIds.containsKey(party)
                    || Sets.symmetricDifference(memberIds.get(party), partyMemberIds.get(party)).size() > 0) {
                hasChanged = true;
                partyMemberIds.put(party, memberIds.get(party));
                LOGGER.debug("Updated list for {} with {} ids", party, memberIds.get(party).size());
            }
        }
    }

    if (hasChanged) {
        updateTime = new Date();
        memberParties.clear();
    }
}

From source file:com.streamsets.pipeline.lib.fuzzy.FuzzyMatch.java

public static int getRatio(String s1, String s2) {

    if (s1.length() >= s2.length()) {
        // We need to swap s1 and s2
        String temp = s2;/*from   ww  w . ja  va 2  s  . co  m*/
        s2 = s1;
        s1 = temp;
    }

    // Get alpha numeric characters
    Set<String> set1 = tokenizeString(escapeString(s1));
    Set<String> set2 = tokenizeString(escapeString(s2));

    SetView<String> intersection = Sets.intersection(set1, set2);

    TreeSet<String> sortedIntersection = Sets.newTreeSet(intersection);

    if (LOG.isTraceEnabled()) {
        StringBuilder sortedSb = new StringBuilder();
        for (String s : sortedIntersection) {
            sortedSb.append(s).append(" ");
        }
        LOG.trace("Sorted intersection --> {}", sortedSb.toString());
    }

    // Find out difference of sets set1 and intersection of set1,set2
    SetView<String> restOfSet1 = Sets.symmetricDifference(set1, intersection);

    // Sort it
    TreeSet<String> sortedRestOfSet1 = Sets.newTreeSet(restOfSet1);

    SetView<String> restOfSet2 = Sets.symmetricDifference(set2, intersection);
    TreeSet<String> sortedRestOfSet2 = Sets.newTreeSet(restOfSet2);

    if (LOG.isTraceEnabled()) {
        StringBuilder sb1 = new StringBuilder();
        for (String s : sortedRestOfSet1) {
            sb1.append(s).append(" ");
        }
        LOG.trace("Sorted rest of 1 --> {}", sb1.toString());

        StringBuilder sb2 = new StringBuilder();
        for (String s : sortedRestOfSet1) {
            sb2.append(s).append(" ");
        }
        LOG.trace("Sorted rest of 2 --> {}", sb2.toString());
    }

    StringBuilder t0Builder = new StringBuilder("");
    StringBuilder t1Builder = new StringBuilder("");
    StringBuilder t2Builder = new StringBuilder("");

    for (String s : sortedIntersection) {
        t0Builder.append(" ").append(s);
    }
    String t0 = t0Builder.toString().trim();

    Set<String> setT1 = Sets.union(sortedIntersection, sortedRestOfSet1);
    for (String s : setT1) {
        t1Builder.append(" ").append(s);
    }
    String t1 = t1Builder.toString().trim();

    Set<String> setT2 = Sets.union(intersection, sortedRestOfSet2);
    for (String s : setT2) {
        t2Builder.append(" ").append(s);
    }

    String t2 = t2Builder.toString().trim();

    int amt1 = calculateLevenshteinDistance(t0, t1);
    int amt2 = calculateLevenshteinDistance(t0, t2);
    int amt3 = calculateLevenshteinDistance(t1, t2);

    LOG.trace("t0 = {} --> {}", t0, amt1);
    LOG.trace("t1 = {} --> {}", t1, amt2);
    LOG.trace("t2 = {} --> {}", t2, amt3);

    return Math.max(Math.max(amt1, amt2), amt3);
}

From source file:tech.beshu.ror.acl.blocks.rules.impl.ZeroKnowledgeIndexFilter.java

public Set<String> alterIndicesIfNecessary(Set<String> indices, MatcherWithWildcards matcher) {

    boolean shouldReplace = false;

    indices = Sets.newHashSet(indices);//from   w  ww.  jav  a 2  s.  c om
    if (indices.contains("_all")) {
        indices.remove("_all");
        indices.add("*");
    }
    if (indices.size() == 0) {
        indices.add("*");
    }

    if (indices.contains("*")) {
        if (!remoteClusterAware) {
            return matcher.getMatchers();
        }
        if (indices.size() == 1) {
            return matcher.getMatchers().stream().filter(m -> !m.contains(":")).collect(Collectors.toSet());
        } else {
            shouldReplace = true;
            indices.remove("*");
            indices.addAll(
                    matcher.getMatchers().stream().filter(m -> !m.contains(":")).collect(Collectors.toSet()));
        }
    }

    Set<String> newIndices = Sets.newHashSet();
    for (String i : indices) {
        if (matcher.match(remoteClusterAware, i)) {
            newIndices.add(i);
            continue;
        }

        MatcherWithWildcards revMatcher = new MatcherWithWildcards(Sets.newHashSet(i));
        Set<String> matched = revMatcher.filter(remoteClusterAware, matcher.getMatchers());

        if (!matched.isEmpty()) {
            newIndices.addAll(matched);
            shouldReplace = true;
        }
    }
    if (shouldReplace || !Sets.symmetricDifference(newIndices, indices).isEmpty()) {
        return newIndices;
    } else {
        return null;
    }
}

From source file:org.codice.ddf.catalog.ui.metacard.workspace.WorkspaceMetacardImpl.java

/**
 * Compute the symmetric difference between the sharing permissions of two workspaces.
 *
 * @param m - metacard to diff against//ww  w.  j a v a 2  s .  c o m
 * @return
 */
public Set<String> diffSharing(Metacard m) {
    if (isWorkspaceMetacard(m)) {
        return Sets.symmetricDifference(getSharing(), from(m).getSharing());
    }
    return Collections.emptySet();
}

From source file:org.apache.metron.bolt.JoinBolt.java

@SuppressWarnings("unchecked")
@Override//from   w  w w .j ava  2s  .  co  m
public void execute(Tuple tuple) {
    String streamId = tuple.getSourceStreamId();
    String key = (String) tuple.getValueByField("key");
    V message = (V) tuple.getValueByField("message");
    try {
        Map<String, V> streamMessageMap = cache.get(key);
        if (streamMessageMap.containsKey(streamId)) {
            LOG.warn(String.format("Received key %s twice for " + "stream %s", key, streamId));
        }
        streamMessageMap.put(streamId, message);
        Set<String> streamIds = getStreamIds(message);
        Set<String> streamMessageKeys = streamMessageMap.keySet();
        if (streamMessageKeys.size() == streamIds.size()
                && Sets.symmetricDifference(streamMessageKeys, streamIds).isEmpty()) {
            collector.emit("message", tuple, new Values(key, joinMessages(streamMessageMap)));
            collector.ack(tuple);
            cache.invalidate(key);
        } else {
            cache.put(key, streamMessageMap);
        }
    } catch (ExecutionException e) {
        collector.reportError(e);
        LOG.error(e.getMessage(), e);
    }
}

From source file:org.lisapark.octopus.core.ModelBean.java

/**
 *
 * @param bean//from w  w  w.java  2 s .c  om
 * @return
 */
public Double compareByProcessors(ModelBean bean) {

    Double tolerance = null;

    Set<String> thisProcs = this.getProcessors();
    Set<String> thatProcs = bean.getProcessors();

    int diff = Sets.symmetricDifference(thisProcs, thatProcs).size();
    int union = Sets.union(thisProcs, thatProcs).size();

    if (union > 0) {
        tolerance = (double) diff / (double) union;
    }

    return tolerance;
}

From source file:org.codice.ddf.catalog.ui.security.accesscontrol.AccessControlUtil.java

/**
 * Does a diff between the old set of values on the specified {@link Metacard} {@link Attribute}
 * with the new set to see if a value was added, removed, or otherwise altered.
 *
 * @param oldMetacard the old version of the metacard that contains the attribute to check.
 * @param newMetacard the new version of the metacard that contains the attribute to check.
 * @param attribute the name of the attribute to check.
 * @return true if the given attribute changed across versions of the metacard, false otherwise.
 *//*from   w w w.j av  a2 s.  com*/
private static boolean attributeHasChanged(Metacard oldMetacard, Metacard newMetacard, String attribute) {
    return !Sets.symmetricDifference(ATTRIBUTE_TO_SET.apply(oldMetacard, attribute),
            ATTRIBUTE_TO_SET.apply(newMetacard, attribute)).isEmpty();
}

From source file:org.sosy_lab.cpachecker.cpa.bdd.BDDPartitionOrderer.java

/** This function collects some edges, that are dependent from the assumption,
 * and puts them into the graph. */
private void collectDependentPartitions(CAssumeEdge assumption) {
    CFANode root = assumption.getPredecessor();
    assert root.getNumLeavingEdges() == 2 : "assumption must have 2 branches.";

    CFAEdge ass1 = root.getLeavingEdge(0);
    CFAEdge ass2 = root.getLeavingEdge(1);
    assert ass1 == assumption || ass2 == assumption;

    Partition assPartition = varClass.getPartitionForEdge(ass1);
    assert varClass.getPartitionForEdge(ass2) == assPartition;

    if (assPartition == null) {
        return;/*from   w  ww  .  ja  va2s  .com*/
    } // assumption is like "3==4"

    // left branch
    CFAUntilSplitCollector fCol1 = new CFAUntilSplitCollector();
    CFATraversal.dfs().ignoreSummaryEdges().traverseOnce(ass1.getSuccessor(), fCol1);
    Set<CFAEdge> reachable1 = fCol1.getEdges();

    // right branch
    CFAUntilSplitCollector fCol2 = new CFAUntilSplitCollector();
    CFATraversal.dfs().ignoreSummaryEdges().traverseOnce(ass2.getSuccessor(), fCol2);
    Set<CFAEdge> reachable2 = fCol2.getEdges();

    // get edges, that are either in left or in right branch.
    // edges, that are reachable from both branches, are independent from the assumption
    SetView<CFAEdge> distinctEdges = Sets.symmetricDifference(reachable1, reachable2);
    for (CFAEdge edge : distinctEdges) {
        if (edge instanceof FunctionCallEdge) {
            final FunctionCallEdge funcCall = (FunctionCallEdge) edge;
            for (int i = 0; i < funcCall.getArguments().size(); i++) {
                final Partition part = varClass.getPartitionForParameterOfEdge(funcCall, i);
                if (part != null) {
                    graph.put(assPartition, part);
                }
            }
        } else {
            final Partition part = varClass.getPartitionForEdge(edge);
            if (part != null) {
                graph.put(assPartition, part);
            }
        }
    }
}

From source file:io.atomix.core.tree.impl.DefaultDocumentTreeNode.java

@Override
public boolean equals(Object obj) {
    if (obj instanceof DefaultDocumentTreeNode) {
        DefaultDocumentTreeNode<V> that = (DefaultDocumentTreeNode<V>) obj;
        if (this.parent.equals(that.parent)) {
            if (this.children.size() == that.children.size()) {
                return Sets.symmetricDifference(this.children.keySet(), that.children.keySet()).isEmpty();
            }/*from ww w .  j  a  va 2  s .co m*/
        }
    }
    return false;
}