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

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

Introduction

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

Prototype

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

Source Link

Document

Returns an unmodifiable view of the union of two sets.

Usage

From source file:com.google.gerrit.server.index.change.StalenessChecker.java

@VisibleForTesting
static boolean refsAreStale(GitRepositoryManager repoManager, Change.Id id,
        SetMultimap<Project.NameKey, RefState> states,
        ListMultimap<Project.NameKey, RefStatePattern> patterns) {
    Set<Project.NameKey> projects = Sets.union(states.keySet(), patterns.keySet());

    for (Project.NameKey p : projects) {
        if (refsAreStale(repoManager, id, p, states, patterns)) {
            return true;
        }/*w w w .  j  a  va  2 s .  co m*/
    }

    return false;
}

From source file:com.opengamma.strata.function.calculation.fra.AbstractFraFunction.java

@Override
public FunctionRequirements requirements(FraTrade trade) {
    Fra fra = trade.getProduct();//from   w  w  w . j  av a 2 s  .  c o  m

    // Create a set of all indices referenced by the FRA
    Set<IborIndex> indices = new HashSet<>();

    // The main index is always present
    indices.add(fra.getIndex());

    // The index used for linear interpolation is optional
    fra.getIndexInterpolated().ifPresent(indices::add);

    // Create a key identifying the rate of each index referenced by the FRA
    Set<ObservableKey> indexRateKeys = indices.stream().map(IndexRateKey::of).collect(toImmutableSet());

    // Create a key identifying the forward curve of each index referenced by the FRA
    Set<MarketDataKey<?>> indexCurveKeys = indices.stream().map(IborIndexCurveKey::of)
            .collect(toImmutableSet());

    // Create a key identifying the discount factors for the FRA currency
    Set<DiscountCurveKey> discountFactorsKeys = ImmutableSet.of(DiscountCurveKey.of(fra.getCurrency()));

    return FunctionRequirements.builder()
            .singleValueRequirements(Sets.union(indexCurveKeys, discountFactorsKeys))
            .timeSeriesRequirements(indexRateKeys).outputCurrencies(fra.getCurrency()).build();
}

From source file:org.gradle.internal.component.AmbiguousConfigurationSelectionException.java

static void formatConfiguration(StringBuilder sb, AttributeContainer fromConfigurationAttributes,
        AttributesSchema consumerSchema, List<ConfigurationMetadata> matches, Set<String> requestedAttributes,
        int maxConfLength, final String conf) {
    Optional<ConfigurationMetadata> match = Iterables.tryFind(matches, new Predicate<ConfigurationMetadata>() {
        @Override/*from   ww  w  .j  a v a 2  s.c om*/
        public boolean apply(ConfigurationMetadata input) {
            return conf.equals(input.getName());
        }
    });
    if (match.isPresent()) {
        AttributeContainer producerAttributes = match.get().getAttributes();
        Set<Attribute<?>> targetAttributes = producerAttributes.keySet();
        Set<String> targetAttributeNames = Sets
                .newTreeSet(Iterables.transform(targetAttributes, ATTRIBUTE_NAME));
        Set<Attribute<?>> allAttributes = Sets.union(fromConfigurationAttributes.keySet(),
                producerAttributes.keySet());
        Set<String> commonAttributes = Sets.intersection(requestedAttributes, targetAttributeNames);
        Set<String> consumerOnlyAttributes = Sets.difference(requestedAttributes, targetAttributeNames);
        sb.append("   ").append("- Configuration '").append(StringUtils.rightPad(conf + "'", maxConfLength + 1))
                .append(" :");
        List<Attribute<?>> sortedAttributes = Ordering.usingToString().sortedCopy(allAttributes);
        List<String> values = new ArrayList<String>(sortedAttributes.size());
        formatAttributes(sb, fromConfigurationAttributes, consumerSchema, producerAttributes, commonAttributes,
                consumerOnlyAttributes, sortedAttributes, values);
    }
}

From source file:com.facebook.buck.haskell.HaskellLibraryDescription.java

private BuildTarget getBaseBuildTarget(BuildTarget target) {
    return target.withoutFlavors(Sets.union(Type.FLAVOR_VALUES, cxxPlatforms.getFlavors()));
}

From source file:org.fenixedu.bennu.core.groups.UserGroup.java

@Override
public Group or(Group group) {
    if (group instanceof UserGroup) {
        return UserGroup.of(Sets.union(members(), ((UserGroup) group).members()));
    }//from ww  w  .j a va  2 s.  c om
    return super.or(group);
}

From source file:com.puppetlabs.geppetto.pp.dsl.ui.container.PPWorkspaceProjectsState.java

/**
 * Produce the union of two lists//from w  w  w .  j a v a2  s.c  o  m
 * 
 * @param a
 * @param b
 * @return a U b
 */
private List<String> union(List<String> a, List<String> b) {
    List<String> theSmallerList = (a.size() < b.size()) ? a : b;
    List<String> theLargerList = (a.size() < b.size()) ? b : a;

    // can be optimized for empty cases and when lists are very small
    if (theSmallerList.isEmpty())
        return theLargerList;
    if (theLargerList.isEmpty())
        return theSmallerList;

    // TODO: small case - probably faster to just check if the larger list contains things from
    // the smaller list

    // Use hashsets as this is faster when there are more than a few entries
    // API doc state that it is faster to give the smaller list as the first argument to union
    return Lists.newArrayList(Sets.union(Sets.newHashSet(theSmallerList), Sets.newHashSet(theLargerList)));
}

From source file:org.eclipse.milo.opcua.stack.core.serialization.DelegateRegistry.java

private static void loadGeneratedClasses(ClassLoader classLoader) throws IOException, ClassNotFoundException {
    ClassPath classPath = ClassPath.from(classLoader);

    ImmutableSet<ClassInfo> structures = classPath
            .getTopLevelClasses("org.eclipse.milo.opcua.stack.core.types.structured");

    ImmutableSet<ClassInfo> enumerations = classPath
            .getTopLevelClasses("org.eclipse.milo.opcua.stack.core.types.enumerated");

    for (ClassInfo classInfo : Sets.union(structures, enumerations)) {
        Class<?> clazz = classInfo.load();
        Class.forName(clazz.getName(), true, classLoader);
    }/*w w  w  . ja  v a2 s  . c  o m*/
}

From source file:com.opengamma.strata.function.calculation.rate.fra.AbstractFraFunction.java

@Override
public FunctionRequirements requirements(FraTrade trade) {
    Fra fra = trade.getProduct();//  w  ww . j  a v a 2 s.co  m

    // Create a set of all indices referenced by the FRA
    Set<IborIndex> indices = new HashSet<>();

    // The main index is always present
    indices.add(fra.getIndex());

    // The index used for linear interpolation is optional
    fra.getIndexInterpolated().ifPresent(indices::add);

    // Create a key identifying the rate of each index referenced by the FRA
    Set<ObservableKey> indexRateKeys = indices.stream().map(IndexRateKey::of).collect(toImmutableSet());

    // Create a key identifying the forward curve of each index referenced by the FRA
    Set<MarketDataKey<?>> indexCurveKeys = indices.stream().map(IborIndexRatesKey::of)
            .collect(toImmutableSet());

    // Create a key identifying the discount factors for the FRA currency
    Set<DiscountFactorsKey> discountFactorsKeys = ImmutableSet.of(DiscountFactorsKey.of(fra.getCurrency()));

    return FunctionRequirements.builder()
            .singleValueRequirements(Sets.union(indexCurveKeys, discountFactorsKeys))
            .timeSeriesRequirements(indexRateKeys).outputCurrencies(fra.getCurrency()).build();
}

From source file:org.onosproject.store.resource.impl.UnifiedDiscreteResources.java

@Override
public DiscreteResources add(DiscreteResources other) {
    if (other instanceof UnifiedDiscreteResources) {
        UnifiedDiscreteResources cast = (UnifiedDiscreteResources) other;
        return new UnifiedDiscreteResources(this.generics.add(cast.generics),
                this.encodables.add(cast.encodables));
    } else if (other instanceof EmptyDiscreteResources) {
        return this;
    }/*w w w .  ja v a 2  s.  co  m*/

    return of(Sets.union(this.values(), other.values()));
}

From source file:com.wrmsr.wava.transform.Outlining.java

public static OutlinedFunction outlineFunction(Function function, Node node, Name outlinedName,
        Index externalRetControl, Index externalRetValue, LocalAnalysis loa, ControlTransferAnalysis cfa,
        ValueTypeAnalysis vta, Map<Node, Optional<Node>> parentsByNode, Map<Name, Node> nodesByName) {
    final List<Index> allLocals;
    final List<Index> spilledOutLocalPuts;
    final List<Index> spilledInLocalGets;
    {/*from  w  w w . j a v a  2  s  .c  o  m*/
        ImSet<Index> entryLocalGets = loa.get(node).getLocalGets();
        ImSet<Index> entryLocalPuts = loa.get(node).getLocalPuts();

        ImSet<Index> nonEntryLocalGets = LocalAnalysis.EMPTY_LOCALS;
        ImSet<Index> nonEntryLocalPuts = LocalAnalysis.EMPTY_LOCALS;
        Optional<Node> cur = Optional.of(node);
        while (true) {
            Optional<Node> next = requireNonNull(parentsByNode.get(cur.get()));
            if (!next.isPresent()) {
                break;
            }
            for (Node sibling : next.get().getChildren()) {
                if (sibling == cur.get()) {
                    continue;
                }
                nonEntryLocalGets = nonEntryLocalGets.union(loa.get(sibling).getLocalGets());
                nonEntryLocalPuts = nonEntryLocalPuts.union(loa.get(sibling).getLocalPuts());
            }
            cur = next;
        }

        Set<Index> entryLocals = Sets.union(entryLocalGets, entryLocalPuts);
        Set<Index> nonEntryLocals = Sets.union(nonEntryLocalGets, nonEntryLocalPuts);
        Set<Index> entryOnlyLocals = Sets.difference(entryLocals, nonEntryLocals);

        Set<Index> spilledOutLocalPutsSet = Sets.intersection(entryLocalPuts, nonEntryLocalGets);
        spilledOutLocalPuts = spilledOutLocalPutsSet.stream().sorted().collect(toImmutableList());
        spilledInLocalGets = Sets.intersection(nonEntryLocalPuts, entryLocalGets).stream()
                .filter(i -> !spilledOutLocalPutsSet.contains(i)).sorted().collect(toImmutableList());

        List<Index> entryOnlyLocalList = entryOnlyLocals.stream().sorted().collect(toImmutableList());
        checkState(
                Sets.intersection(ImmutableSet.copyOf(spilledInLocalGets), ImmutableSet.copyOf(entryOnlyLocals))
                        .isEmpty());

        allLocals = ImmutableList.<Index>builder().addAll(spilledOutLocalPuts).addAll(spilledInLocalGets)
                .addAll(entryOnlyLocalList).build();
    }

    Map<Index, Index> localTranslationMap = enumerate(allLocals.stream())
            .collect(toImmutableMap(i -> i.getItem(), i -> Index.of(i.getIndex())));

    ControlTransferAnalysis.Entry maxCfa = cfa.get(node);
    List<ControlTransferAnalysis.Target> targets = ImmutableList.copyOf(maxCfa.getTargets());
    Map<ControlTransferAnalysis.Target, Name> targetNameMap = enumerate(targets.stream())
            .collect(toImmutableMap(i -> i.getItem(), i -> Name.of("_epilog$" + i.getIndex())));

    ImmutableMap.Builder<ControlTransferAnalysis.Target, Type> targetTypesBuilder = ImmutableMap.builder();
    for (ControlTransferAnalysis.Target target : targets) {
        if (target.equals(ControlTransferAnalysis.Target.RETURN)) {
            targetTypesBuilder.put(ControlTransferAnalysis.Target.RETURN, function.getResult());
        } else if (target instanceof ControlTransferAnalysis.NameTarget) {
            Name name = ((ControlTransferAnalysis.NameTarget) target).getName();
            Type type = vta.get(nodesByName.get(name)).getType();
            targetTypesBuilder.put(target, type);
        } else {
            throw new IllegalStateException();
        }
    }
    Map<ControlTransferAnalysis.Target, Type> targetTypes = targetTypesBuilder.build();

    Node outlinedBody = node.accept(new Visitor<Void, Node>() {
        @Override
        protected Node visitNode(Node node, Void context) {
            return reconstructNode(node,
                    node.getChildren().stream().map(child -> child.accept(this, context)).iterator());
        }

        @Override
        public Node visitBreak(Break node, Void context) {
            ControlTransferAnalysis.Target target = ControlTransferAnalysis.Target.of(node.getTarget());
            if (targetNameMap.containsKey(target)) {
                return new Break(targetNameMap.get(ControlTransferAnalysis.Target.of(node.getTarget())),
                        node.getValue().accept(this, context));
            } else {
                return super.visitBreak(node, context);
            }
        }

        @Override
        public Node visitBreakTable(BreakTable node, Void context) {
            return super.visitBreakTable(node, context);
        }

        @Override
        public Node visitGetLocal(GetLocal node, Void context) {
            return new GetLocal(localTranslationMap.get(node.getIndex()), node.getType());
        }

        @Override
        public Node visitReturn(Return node, Void context) {
            return new Break(targetNameMap.get(ControlTransferAnalysis.Target.RETURN),
                    node.getValue().accept(this, context));
        }

        @Override
        public Node visitSetLocal(SetLocal node, Void context) {
            return new SetLocal(localTranslationMap.get(node.getIndex()), node.getType(),
                    node.getValue().accept(this, context));
        }
    }, null);

    Index internalRetControl = Index.of(allLocals.size());
    Index internalRetValue = Index.of(allLocals.size() + 1);

    ValueTypeAnalysis.Entry maxVta = vta.get(node);
    if (maxCfa.getExecution() == ControlTransferAnalysis.Execution.FALLTHROUGH) {
        if (maxVta.getType() != Type.NONE) {
            outlinedBody = new Block(ImmutableList.of(
                    new SetLocal(internalRetValue, Type.I64, packI64(outlinedBody, maxVta.getType())),
                    new Break(Name.of("_epilog$"), new Nop())));
        } else {
            outlinedBody = new Block(ImmutableList.of(outlinedBody, new Break(Name.of("_epilog$"), new Nop())));
        }
    }

    for (int i = 0; i < targets.size(); ++i) {
        ControlTransferAnalysis.Target target = targets.get(i);
        Name name = targetNameMap.get(target);
        Type type = targetTypes.get(target);

        outlinedBody = new Label(name, outlinedBody);

        switch (type) {
        case NONE:
            break;
        case I32:
        case I64:
        case F32:
        case F64:
            outlinedBody = new SetLocal(internalRetValue, Type.I64, packI64(outlinedBody, type));
            break;
        default:
            throw new IllegalStateException();
        }

        outlinedBody = new Block(ImmutableList.of(new Block(ImmutableList.of(outlinedBody,
                new SetLocal(internalRetControl, Type.I32, new Const(Literal.of(i))),
                new Break(Name.of("_epilog$"), new Nop())))));
    }

    Node returnValueSpiller = new Call(new Call.HostTarget(HostOp.SpillPut, Optional.empty()),
            HostOp.SpillPut.getSignature(),
            ImmutableList.of(new Const(Literal.of(0)), new GetLocal(internalRetValue, Type.I64)));

    List<Node> localSpillers = enumerate(spilledOutLocalPuts.stream()).map(i -> {
        Type type = function.getLocals().getLocal(i.getItem()).getType();
        return new Call(new Call.HostTarget(HostOp.SpillPut, Optional.empty()), HostOp.SpillPut.getSignature(),
                ImmutableList.of(new Const(Literal.of(i.getIndex() + 1)),
                        packI64(new GetLocal(localTranslationMap.get(i.getItem()), type), type)));
    }).collect(toImmutableList());

    outlinedBody = new Block(ImmutableList.of(
            new Label(Name.of("_epilog$"), outlinedBody), new Block(Stream
                    .concat(Stream.of(returnValueSpiller), localSpillers.stream()).collect(toImmutableList())),
            new Return(new GetLocal(internalRetControl, Type.I32))));

    List<Local> localList = ImmutableList.<Local>builder().addAll(allLocals.stream().map(l -> {
        Local o = function.getLocals().getLocal(l);
        return new Local(o.getName(), localTranslationMap.get(l), o.getType());
    }).iterator()).add(new Local(Name.of("_internal$control"), internalRetControl, Type.I32))
            .add(new Local(Name.of("_internal$value"), internalRetValue, Type.I64)).build();

    int argCount = spilledOutLocalPuts.size() + spilledInLocalGets.size();

    Function outlinedFunction = new Function(outlinedName, Type.I32, argCount, new Locals(localList),
            outlinedBody);

    Node outlinedCall = new SetLocal(externalRetControl, Type.I32,
            new Call(new Call.DirectTarget(outlinedName), outlinedFunction.getSignature(),
                    Stream.concat(spilledOutLocalPuts.stream(), spilledInLocalGets.stream())
                            .map(i -> new GetLocal(i, function.getLocals().getLocal(i).getType()))
                            .collect(toImmutableList())));

    Node returnValueUnspiller = new SetLocal(externalRetValue, Type.I64,
            new Call(new Call.HostTarget(HostOp.SpillGet, Optional.empty()), HostOp.SpillGet.getSignature(),
                    ImmutableList.of(new Const(Literal.of(0)))));

    List<Node> localUnspillers = enumerate(spilledOutLocalPuts.stream()).map(i -> {
        Type type = function.getLocals().getLocal(i.getItem()).getType();
        return new SetLocal(i.getItem(), type,
                unpackI64(new Call(new Call.HostTarget(HostOp.SpillGet, Optional.empty()),
                        HostOp.SpillGet.getSignature(),
                        ImmutableList.of(new Const(Literal.of(i.getIndex() + 1)))), type));
    }).collect(toImmutableList());

    Node controlSwitch = new Switch(new GetLocal(externalRetControl, Type.I32),
            Stream.concat(enumerate(targets.stream()).map(i -> {
                if (i.getItem().equals(ControlTransferAnalysis.Target.RETURN)) {
                    return new Switch.Entry(ImmutableList.of(Switch.Value.of(i.getIndex() + 1)), new Return(
                            unpackI64(new GetLocal(externalRetValue, Type.I64), function.getResult())));
                } else if (i.getItem() instanceof ControlTransferAnalysis.NameTarget) {
                    Name name = ((ControlTransferAnalysis.NameTarget) i.getItem()).getName();
                    Type type = vta.get(nodesByName.get(name)).getType();
                    Node value = type != Type.NONE
                            ? unpackI64(new GetLocal(externalRetValue, Type.I64), function.getResult())
                            : new Nop();
                    return new Switch.Entry(ImmutableList.of(Switch.Value.of(i.getIndex() + 1)),
                            new Break(name, value));
                } else {
                    throw new IllegalStateException();
                }
            }), Stream.concat(
                    Stream.of(new Switch.Entry(ImmutableList.of(Switch.Value.DEFAULT), new Unreachable())),
                    maxCfa.getExecution() == ControlTransferAnalysis.Execution.FALLTHROUGH
                            ? Stream.of(new Switch.Entry(ImmutableList.of(Switch.Value.of(0)), new Nop()))
                            : Stream.empty()))
                    .collect(toImmutableList()));

    Node callsite = new Block(ImmutableList.<Node>builder().add(outlinedCall).add(returnValueUnspiller)
            .addAll(localUnspillers).add(controlSwitch)
            .add(maxCfa.getExecution() == ControlTransferAnalysis.Execution.FALLTHROUGH
                    ? unpackI64(new GetLocal(externalRetControl, Type.I64), maxVta.getType())
                    : new Nop())
            .build());

    return new OutlinedFunction(callsite, outlinedFunction);
}