Example usage for java.util Set retainAll

List of usage examples for java.util Set retainAll

Introduction

In this page you can find the example usage for java.util Set retainAll.

Prototype

boolean retainAll(Collection<?> c);

Source Link

Document

Retains only the elements in this set that are contained in the specified collection (optional operation).

Usage

From source file:juicebox.data.HiCFileTools.java

/**
 * Set intersection/*from  ww w . j a va2 s . c o  m*/
 * http://stackoverflow.com/questions/7574311/efficiently-compute-intersection-of-two-sets-in-java
 *
 * @param set1
 * @param set2
 * @return intersection of set1 and set2
 */
public static Set<Chromosome> getSetIntersection(Set<Chromosome> set1, Set<Chromosome> set2) {
    boolean set1IsLarger = set1.size() > set2.size();
    Set<Chromosome> cloneSet = new HashSet<Chromosome>(set1IsLarger ? set2 : set1);
    cloneSet.retainAll(set1IsLarger ? set1 : set2);
    return cloneSet;
}

From source file:com.net2plan.utils.CollectionUtils.java

/**
 * Returns the intersection set of a series of input collections. There is no order guarantee.
 *
 * @param <A> Key type/* w w  w .ja  v a  2  s  .co m*/
 * @param collections Series of input collections
 * @return Intersection set of input collections
 */
public static <A> Set<A> intersect(Collection<A>... collections) {
    if (collections.length == 0)
        return new LinkedHashSet<A>();

    Set<A> intersectionSet = new LinkedHashSet<A>();
    intersectionSet.addAll(collections[0]);

    for (int i = 1; i < collections.length; i++) {
        intersectionSet.retainAll(collections[i]);
    }

    return intersectionSet;
}

From source file:org.bibsonomy.webapp.controller.ResourceListController.java

protected static <T> Set<T> intersection(final Collection<? extends T> col1,
        final Collection<? extends T> col2) {
    if (!present(col1) || !present(col2)) {
        return Collections.emptySet();
    }/*from  w w  w  . j  a va  2 s .c om*/

    final Set<T> set = new HashSet<T>(col1);
    set.retainAll(col2);
    return set;
}

From source file:ubic.BAMSandAllen.Util.java

public static Collection<?> intersect(Collection<?>... collections) {
    // make a new set so it doesnt modifiy the parameter sets
    Set<?> intersect = new HashSet<Object>(collections[0]);
    for (int i = 1; i < collections.length; i++) {
        intersect.retainAll(collections[i]);
    }//from ww w .  j  a v a 2  s  . c  o  m
    return intersect;
}

From source file:org.zkoss.spring.security.SecurityUtil.java

/**
 * Find the common authorities between the current authentication's {@link GrantedAuthority} and the ones
 * that have been specified in the tag's ifAny, ifNot or ifAllGranted attributes.<p>We need to manually
 * iterate over both collections, because the granted authorities might not implement {@link
 * Object#equals(Object)} and {@link Object#hashCode()} in the same way as {@link GrantedAuthorityImpl}, thereby
 * invalidating {@link Collection#retainAll(java.util.Collection)} results.</p>
 * <p>/*from   w ww .j a  v  a2  s  .  co m*/
 * <strong>CAVEAT</strong>:  This method <strong>will not</strong> work if the granted authorities
 * returns a <code>null</code> string as the return value of {@link
 * org.springframework.security.GrantedAuthority#getAuthority()}.
 * </p>
 * <p>Reported by rawdave, on Fri Feb 04, 2005 2:11 pm in the Spring Security forum.</p>
 *
 * @param granted The authorities granted by the authentication. May be any implementation of {@link
 *        GrantedAuthority} that does <strong>not</strong> return <code>null</code> from {@link
 *        org.springframework.security.GrantedAuthority#getAuthority()}.
 * @param required A {@link Set} of {@link GrantedAuthorityImpl}s that have been built using ifAny, ifAll or
 *        ifNotGranted.
 *
 * @return A set containing only the common authorities between <var>granted</var> and <var>required</var>.
 */
private static Set retainAll(final Collection<? extends GrantedAuthority> granted,
        final Collection<GrantedAuthority> required) {
    Set grantedRoles = authoritiesToRoles(granted);
    Set requiredRoles = authoritiesToRoles(required);
    grantedRoles.retainAll(requiredRoles);

    return rolesToAuthorities(grantedRoles, granted);
}

From source file:io.fabric8.forge.rest.dto.UICommands.java

public static void populateController(Map<String, Object> requestedInputs, CommandController controller,
        ConverterFactory converterFactory) {
    Map<String, InputComponent<?, ?>> inputs = controller.getInputs();
    Set<String> inputKeys = new HashSet<>(inputs.keySet());
    if (requestedInputs != null) {
        inputKeys.retainAll(requestedInputs.keySet());
        Set<Map.Entry<String, InputComponent<?, ?>>> entries = inputs.entrySet();
        for (Map.Entry<String, InputComponent<?, ?>> entry : entries) {
            String key = entry.getKey();
            InputComponent<?, ?> component = entry.getValue();
            Object value = requestedInputs.get(key);
            String textValue = null;
            if (value instanceof String || value instanceof Number || value instanceof Date) {
                textValue = value.toString();
            }//  www  .  j  a v a2  s  .  c o  m
            /*
                            String textValue = requestedInputs.get(key);
                            Object value = textValue;
            */
            if (component != null && textValue != null) {
                Converter<String, ?> valueConverter = component.getValueConverter();
                if (valueConverter != null) {
                    value = valueConverter.convert(textValue);
                } else {
                    Class<?> valueType = component.getValueType();
                    if (valueType.isEnum()) {
                        Class<? extends Enum> enumType = (Class<? extends Enum>) valueType;
                        value = Enum.valueOf(enumType, textValue);
                    }
                }
                InputComponents.setValueFor(converterFactory, component, value);
            } else {
                controller.setValueFor(key, value);
            }

            Object actual = controller.getValueFor(key);
        }
    }
}

From source file:it.infn.ct.downtime.Downtime.java

public static String[] getIntersection(String[] arr1, String[] arr2) {
    Set<String> s1 = new HashSet<String>(Arrays.asList(arr1));
    Set<String> s2 = new HashSet<String>(Arrays.asList(arr2));
    s1.retainAll(s2);

    String[] result = s1.toArray(new String[s1.size()]);

    return result;
}

From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_Buckets.java

/** Want to end up with 3 lists:
 *  - v1 sources that don't exist in v2 (Create them)
 *  - v2 sources that don't exist in v1 (Delete them)
 *  - matching v1/v2 sources with different modified times (Update them)
 * @param to_compare/*w w w  .j  a  v a  2s .co  m*/
 * @returns a 3-tuple with "to create", "to delete", "to update"
 */
protected static Tuple3<Collection<String>, Collection<String>, Collection<String>> compareSourcesToBuckets_categorize(
        final Tuple2<Map<String, String>, Map<String, Date>> to_compare) {

    // Want to end up with 3 lists:
    // - v1 sources that don't exist in v2 (Create them)
    // - v2 sources that don't exist in v1 (Delete them)
    // - matching v1/v2 sources with different modified times (Update them)

    // (do delete first, then going to filter to_compare._1() on value==null)      
    final Set<String> v2_not_v1 = new HashSet<String>(to_compare._2().keySet());
    v2_not_v1.removeAll(to_compare._1().keySet());

    // OK not worried about deletes any more, not interested in isApproved:false

    final Set<String> to_compare_approved = to_compare._1().entrySet().stream()
            .filter(kv -> null != kv.getValue() && !kv.getValue().isEmpty()).map(kv -> kv.getKey())
            .collect(Collectors.toSet());

    final Set<String> v1_and_v2 = new HashSet<String>(to_compare_approved);
    v1_and_v2.retainAll(to_compare._2().keySet());

    final List<String> v1_and_v2_mod = v1_and_v2.stream().filter(id -> {
        try {
            final Date v1_date = parseJavaDate(to_compare._1().get(id));
            final Date v2_date = to_compare._2().get(id);
            return v1_date.getTime() > v2_date.getTime();
        } catch (Throwable e) {
            return false; // (just ignore)
        }
    }).collect(Collectors.toList());

    final Set<String> v1_not_v2 = new HashSet<String>(to_compare_approved);
    v1_not_v2.removeAll(to_compare._2().keySet());

    return Tuples._3T(v1_not_v2, v2_not_v1, v1_and_v2_mod);
}

From source file:org.apache.asterix.optimizer.rules.util.EquivalenceClassUtils.java

/**
 * Find the header variables that can imply all subplan-local live variables at <code>operator</code>.
 *
 * @param operator/*  w  w  w . j av a2 s  .c  o m*/
 *            the operator of interest.
 * @param usedForCorrelationJoin
 *            whether the generated primary key will be used for a join that recovers the correlation.
 * @param context
 *            the optimization context.
 * @return Pair<ILogicalOperator, Set<LogicalVariable>>, an operator (which is either the original parameter
 *         <code>operator</code> or a newly created operator) and
 *         a set of primary key variables at the operator.
 * @throws AlgebricksException
 */
public static Pair<ILogicalOperator, Set<LogicalVariable>> findOrCreatePrimaryKeyOpAndVariables(
        ILogicalOperator operator, boolean usedForCorrelationJoin, IOptimizationContext context)
        throws AlgebricksException {
    computePrimaryKeys(operator, context);

    Set<LogicalVariable> liveVars = new HashSet<>();
    VariableUtilities.getSubplanLocalLiveVariables(operator, liveVars);

    Set<LogicalVariable> primaryKeyVars = new HashSet<>();
    Set<LogicalVariable> noKeyVars = new HashSet<>();
    for (LogicalVariable liveVar : liveVars) {
        List<LogicalVariable> keyVars = context.findPrimaryKey(liveVar);
        if (keyVars != null) {
            keyVars.retainAll(liveVars);
        }
        if ((keyVars == null || keyVars.isEmpty())) {
            noKeyVars.add(liveVar);
        } else {
            primaryKeyVars.addAll(keyVars);
        }
    }
    primaryKeyVars.retainAll(liveVars);
    if (primaryKeyVars.containsAll(noKeyVars)) {
        return new Pair<ILogicalOperator, Set<LogicalVariable>>(operator, primaryKeyVars);
    } else {
        LogicalVariable assignVar = context.newVar();
        ILogicalOperator assignOp = new AssignOperator(assignVar,
                new MutableObject<ILogicalExpression>(new StatefulFunctionCallExpression(
                        FunctionUtil.getFunctionInfo(AsterixBuiltinFunctions.CREATE_QUERY_UID), null)));
        OperatorPropertiesUtil.markMovable(assignOp, !usedForCorrelationJoin);
        assignOp.getInputs().add(new MutableObject<ILogicalOperator>(operator));
        context.addPrimaryKey(new FunctionalDependency(Collections.singletonList(assignVar),
                new ArrayList<LogicalVariable>(liveVars)));
        context.computeAndSetTypeEnvironmentForOperator(assignOp);
        return new Pair<ILogicalOperator, Set<LogicalVariable>>(assignOp, Collections.singleton(assignVar));
    }
}

From source file:org.intermine.metadata.DescriptorUtils.java

/**
 * Return a list of the classes which present in the inheritance tree of all the given
 * classes. If more than one is returned, they will be sorted so that the most specific one
 * is at the head of the list.//from  www . j  a va 2s .  c o m
 *
 * ie:, given <code>Employee, Manager, CEO</code>, this method should return
 * a list such as <code>Employee, Employable, HasAddress, Thing</code>. The returned
 * list should never contain <code>InterMineObject</code>. All returned classes are guaranteed
 * to be subclasses of {@link InterMineObject}. The returned list is guaranteed to never
 * be empty.
 *
 * @param classes The classes to investigate.
 * @return A liat of classes common to the inheritance tree of all of them.
 * @throws MetaDataException If
 */
public static List<ClassDescriptor> findCommonClasses(Collection<ClassDescriptor> classes)
        throws MetaDataException {

    if (classes == null) {
        throw new IllegalArgumentException("classes is null");
    }
    if (classes.isEmpty()) {
        throw new MetaDataException("No classes provided");
    }
    if (classes.size() == 1) {
        return new ArrayList<ClassDescriptor>(classes);
    }

    Set<ClassDescriptor> superClasses = null;

    for (ClassDescriptor cd : classes) {
        Set<ClassDescriptor> ancestry = cd.getAllSuperDescriptors();
        ancestry.add(cd);
        // If this is the first one, initialise superClasses with this class and all its parents
        // else, Make superClasses the intersection of the current state of superClasses and the
        // ancestry of the current class.
        if (superClasses == null) {
            superClasses = ancestry;
        } else {
            superClasses.retainAll(ancestry);
        }
    }

    // Make sure all classes are InterMineObjs
    CollectionUtils.filter(classes, new Predicate() {
        @Override
        public boolean evaluate(Object arg0) {
            ClassDescriptor cd = (ClassDescriptor) arg0;
            return cd.getAllSuperclassNames().contains("org.intermine.model.InterMineObject");
        }
    });

    if (superClasses.isEmpty()) {
        throw new MetaDataException("No common type");
    }
    return sortClassesBySpecificity(superClasses);
}