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: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   w  ww.j  a v  a2 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:org.topicquests.ks.tm.CredentialUtility.java

/**
 * <p>Return <code>1</code> if sufficient <code>credentials</code>
 * to allow viewing this <code>node></p>
 * <p>Return <code>0</code> if not sufficient <code>credentials</code></p>
 * <p>Return <code>-1</code> if node has been removed: (isAlive = false)</p>
 * @param node/* ww w  . jav  a  2s.  c om*/
 * @param credentials
 * @return
 */
public int checkCredentials(ISubjectProxy node, ITicket credentials) {
    int what = 1; //default
    if (!node.getIsLive())
        return -1;
    if (node.getIsPrivate()) {
        //node created by this dude?
        String cid = node.getCreatorId();
        if (!cid.equals(credentials.getUserLocator())) {
            //Same avatar?
            boolean found = false;
            List<String> l = credentials.listAvatars();
            if (l != null) {
                if (l.contains(cid))
                    found = true;
            }
            if (!found) {
                //check goup
                Set<String> groupLocators = Sets.newHashSet(credentials.listGroupLocators());
                Set<String> aclValues = Sets.newHashSet(node.listACLValues());
                SetView<String> intersection = Sets.intersection(groupLocators, aclValues);
                found = !intersection.isEmpty();
            }
            if (!found)
                return 0;
        }
    }
    return what;
}

From source file:es.upm.dit.xsdinferencer.merge.mergerimpl.enumeration.MinIntersectionUnidirectionalEnumComparator.java

/**
 * @see EnumComparator#compare(SimpleType, SimpleType)
 *///w  w w  .  ja  v a2 s  .  c  o m
@Override
public boolean compare(SimpleType simpleType1, SimpleType simpleType2) {
    if (!simpleType1.isEnum() || !simpleType2.isEnum())
        return false;
    if (simpleType1.isEmpty() && simpleType2.isEmpty())
        return true;
    Set<String> valuesOfSimpleType1 = ImmutableSet.copyOf(simpleType1);
    Set<String> valuesOfSimpleType2 = ImmutableSet.copyOf(simpleType2);
    Set<String> valuesOfIntersection = Sets.intersection(valuesOfSimpleType1, valuesOfSimpleType2);
    float ratio1 = ((float) valuesOfIntersection.size()) / ((float) valuesOfSimpleType1.size());
    float ratio2 = ((float) valuesOfIntersection.size()) / ((float) valuesOfSimpleType2.size());
    return ratio1 >= threshold || ratio2 >= threshold;
}

From source file:com.siemens.sw360.datahandler.common.SW360Utils.java

public static Set<String> filterBUSet(String organisation, Set<String> strings) {
    if (strings == null || isNullOrEmpty(organisation)) {
        return Collections.emptySet();
    }//w w w.  j ava  2s . co m
    String bu = getBUFromOrganisation(organisation);
    return Sets.intersection(strings, ImmutableSet.of(bu));
}

From source file:com.facebook.buck.tools.consistency.TargetsDiffer.java

/**
 * Prints the differences between two target graphs, including newly added, removed, and changed
 * targets and hashes/*from   w w w  .  j a va 2s  .  com*/
 *
 * @param originalFile The original set of target / hash pairs
 * @param newFile The new set of target / hash pairs
 * @throws MaxDifferencesException If the maximum number of differences (as specified by {@link
 *     #diffPrinter}) is reached
 * @return true if the two targets are different false if they aren't
 */
public DifferState.DiffResult printDiff(ParsedTargetsFile originalFile, ParsedTargetsFile newFile)
        throws MaxDifferencesException {
    Set<String> targetsInOriginal = originalFile.targetsToHash.keySet();
    Set<String> targetsInNew = newFile.targetsToHash.keySet();
    Set<String> targetsOnlyInOriginal = Sets.difference(targetsInOriginal, targetsInNew);
    Set<String> targetsOnlyInNew = Sets.difference(targetsInNew, targetsInOriginal);
    Set<String> targetsInBoth = Sets.intersection(targetsInOriginal, targetsInNew);

    printRemoved(originalFile, targetsOnlyInOriginal);
    printAdded(newFile, targetsOnlyInNew);
    printChanged(originalFile, newFile, targetsInBoth);
    return differState.hasChanges();
}

From source file:org.wso2.carbon.governance.comparator.wsdl.WSDLOperationComparator.java

protected void compareOperations(Definition base, Definition changed, DefaultComparison comparison) {
    DefaultComparison.DefaultSection section = null;
    Set<QName> commonKeys = Sets.intersection(base.getPortTypes().keySet(), changed.getPortTypes().keySet());
    List<Operation> additions = new ArrayList<>();
    List<Operation> removeals = new ArrayList<>();
    List<Operation> leftChanges = new ArrayList<>();
    List<Operation> rightChanges = new ArrayList<>();
    if (commonKeys.size() > 0) {
        for (QName portTypeName : commonKeys) {
            PortType leftPortType = base.getPortType(portTypeName);
            PortType rightPortType = changed.getPortType(portTypeName);
            List<Operation> leftOperations = leftPortType.getOperations();
            List<Operation> rightOperations = rightPortType.getOperations();

            for (Operation left : leftOperations) {
                Operation right = rightPortType.getOperation(left.getName(), null, null);
                if (right != null) {
                    if (isDifferent(left, right)) {
                        leftChanges.add(left);
                        rightChanges.add(right);
                    }// ww w  .  ja v  a 2 s.c o  m
                    rightOperations.remove(right);
                } else if (right == null) {
                    removeals.add(left);
                }
            }
            additions = rightOperations;
        }
    }

    if (section == null && additions.size() > 0) {
        section = comparison.newSection();
    }
    processAdditions(section, additions, changed);

    if (section == null && removeals.size() > 0) {
        section = comparison.newSection();
    }
    processRemovals(section, removeals, base);

    boolean different = false;
    for (int i = 0; i < leftChanges.size(); i++) {
        if (isDifferent(leftChanges.get(i), rightChanges.get(i))) {
            different = true;
            break;
        }
    }

    if (section == null && different) {
        section = comparison.newSection();
    }
    if (different) {
        processChanges(section, leftChanges, rightChanges, base, changed);
    }

    if (section != null) {
        comparison.addSection(ComparatorConstants.WSDL_IMPORTS, section);
    }
}

From source file:net.derquinse.bocas.MemoryBocas.java

@Override
public final Set<ByteString> contained(Iterable<ByteString> keys) {
    final Set<ByteString> requested;
    if (keys instanceof Set) {
        requested = (Set<ByteString>) keys;
    } else {//from  ww w  . ja v  a2  s. co m
        requested = Sets.newHashSet(keys);
    }
    if (requested.isEmpty()) {
        return ImmutableSet.of();
    }
    return Sets.intersection(requested, bucket.keySet()).immutableCopy();
}

From source file:com.addthis.bundle.util.RootField.java

@Override
public void setValue(Bundle bundle, @Nullable ValueObject value) {
    if (value == null) {
        bundle.asMap().replaceAll((a, b) -> null);
    } else if (array || (value.getObjectType() == ValueObject.TYPE.ARRAY)) {
        ValueArray bundleList = bundle.asValueArray();
        ValueArray valueList = value.asArray();
        int bundleSize = bundleList.size();
        int valueSize = valueList.size();
        if (valueSize > bundleSize) {
            bundleList.addAll(bundleSize, valueList.subList(bundleSize, valueSize));
        }//from ww w.ja v  a 2s . com
        for (int i = 0; i < Math.min(bundleSize, valueSize); i++) {
            bundleList.set(i, valueList.get(i));
        }
    } else {
        ValueMap bundleMap = bundle.asValueMap();
        ValueMap valueMap = value.asMap();
        if (!force && !Sets.intersection(bundleMap.keySet(), valueMap.keySet()).isEmpty()) {
            String message = String.format(
                    "Trying to write value map (%s) to bundle root (%s), at least one field already exists and "
                            + "force=false",
                    valueMap, bundle);
            throw new IllegalArgumentException(message);
        }
        bundleMap.putAll(valueMap);
    }
}

From source file:org.apache.marmotta.ldpath.model.selectors.IntersectionSelector.java

/**
 * Apply the selector to the context node passed as argument and return the collection
 * of selected nodes in appropriate order.
 *
 * @param context     the node where to start the selection
 * @param path        the path leading to but not including the context node in the current evaluation of LDPath; may be null,
 *                    in which case path tracking is disabled
 * @param resultPaths a map where each of the result nodes maps to a path leading to the result node in the LDPath evaluation;
 *                    if null, path tracking is disabled and the path argument is ignored
 * @return the collection of selected nodes
 */// w  ww  .  j  a  v  a 2s.  co  m
@Override
public Collection<Node> select(RDFBackend<Node> nodeRDFBackend, Node context, List<Node> path,
        Map<Node, List<Node>> resultPaths) {
    return Sets.intersection(ImmutableSet.copyOf(left.select(nodeRDFBackend, context, path, resultPaths)),
            ImmutableSet.copyOf(right.select(nodeRDFBackend, context, path, resultPaths)));
}

From source file:org.eclipse.umlgen.reverse.c.internal.reconciler.Utils.java

/**
 * This returns only the objects which are only in the given <code>left</code> list.
 *
 * @param left//from  www  . j a  v  a  2s . c  o  m
 *            The left list
 * @param right
 *            The right list
 * @param function
 *            Function which applies on the 2 lists
 * @param <T>
 *            Any Java object
 * @param <X>
 *            Any java object
 * @return The objects only in left side
 */
public static <X, T> Collection<T> inLeftOnly(Collection<T> left, Collection<T> right,
        final Function<? super T, X> function) {
    Set<X> leftSet = ImmutableSet.copyOf(Iterables.transform(left, function));
    Set<X> rigthSet = ImmutableSet.copyOf(Iterables.transform(right, function));

    Set<X> intersection = Sets.intersection(leftSet, rigthSet);
    final Set<X> inLeftOnlyAfterFunction = Sets.difference(leftSet, intersection);

    return Collections2.filter(left, new Predicate<T>() {
        public boolean apply(T input) {
            return inLeftOnlyAfterFunction.contains(function.apply(input));
        }
    });
}