Example usage for com.google.common.collect Maps newHashMapWithExpectedSize

List of usage examples for com.google.common.collect Maps newHashMapWithExpectedSize

Introduction

In this page you can find the example usage for com.google.common.collect Maps newHashMapWithExpectedSize.

Prototype

public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) 

Source Link

Document

Creates a HashMap instance, with a high enough "initial capacity" that it should hold expectedSize elements without growth.

Usage

From source file:org.spongepowered.common.data.processor.data.tileentity.TileEntityCommandDataProcessor.java

@Override
protected Map<Key<?>, ?> getValues(TileEntityCommandBlock entity) {
    CommandBlockLogic logic = entity.getCommandBlockLogic();
    Map<Key<?>, Object> values = Maps.newHashMapWithExpectedSize(4);
    Optional<Text> lastCommandOutput = logic.getLastOutput() != null
            ? Optional.of(SpongeTexts.toText(logic.getLastOutput()))
            : Optional.empty();//from  www .  ja  v  a 2s .  c om
    values.put(Keys.LAST_COMMAND_OUTPUT, lastCommandOutput);
    values.put(Keys.COMMAND, logic.commandStored);
    values.put(Keys.SUCCESS_COUNT, logic.successCount);
    values.put(Keys.TRACKS_OUTPUT, logic.shouldTrackOutput());
    return values;
}

From source file:org.apache.beam.runners.apex.translation.ParDoBoundMultiTranslator.java

@Override
public void translate(ParDo.BoundMulti<InputT, OutputT> transform, TranslationContext context) {
    DoFn<InputT, OutputT> doFn = transform.getFn();
    DoFnSignature signature = DoFnSignatures.getSignature(doFn.getClass());

    if (signature.processElement().isSplittable()) {
        throw new UnsupportedOperationException(String.format("%s does not support splittable DoFn: %s",
                ApexRunner.class.getSimpleName(), doFn));
    }// ww w  .  ja v a  2s  .c  o  m
    if (signature.stateDeclarations().size() > 0) {
        throw new UnsupportedOperationException(
                String.format("Found %s annotations on %s, but %s cannot yet be used with state in the %s.",
                        DoFn.StateId.class.getSimpleName(), doFn.getClass().getName(),
                        DoFn.class.getSimpleName(), ApexRunner.class.getSimpleName()));
    }

    if (signature.timerDeclarations().size() > 0) {
        throw new UnsupportedOperationException(
                String.format("Found %s annotations on %s, but %s cannot yet be used with timers in the %s.",
                        DoFn.TimerId.class.getSimpleName(), doFn.getClass().getName(),
                        DoFn.class.getSimpleName(), ApexRunner.class.getSimpleName()));
    }

    List<TaggedPValue> outputs = context.getOutputs();
    PCollection<InputT> input = (PCollection<InputT>) context.getInput();
    List<PCollectionView<?>> sideInputs = transform.getSideInputs();
    Coder<InputT> inputCoder = input.getCoder();
    WindowedValueCoder<InputT> wvInputCoder = FullWindowedValueCoder.of(inputCoder,
            input.getWindowingStrategy().getWindowFn().windowCoder());

    ApexParDoOperator<InputT, OutputT> operator = new ApexParDoOperator<>(context.getPipelineOptions(), doFn,
            transform.getMainOutputTag(), transform.getSideOutputTags().getAll(),
            ((PCollection<InputT>) context.getInput()).getWindowingStrategy(), sideInputs, wvInputCoder,
            context.<Void>stateInternalsFactory());

    Map<PCollection<?>, OutputPort<?>> ports = Maps.newHashMapWithExpectedSize(outputs.size());
    for (TaggedPValue output : outputs) {
        checkArgument(output.getValue() instanceof PCollection, "%s %s outputs non-PCollection %s of type %s",
                ParDo.BoundMulti.class.getSimpleName(), context.getFullName(), output.getValue(),
                output.getValue().getClass().getSimpleName());
        PCollection<?> pc = (PCollection<?>) output.getValue();
        if (output.getTag().equals(transform.getMainOutputTag())) {
            ports.put(pc, operator.output);
        } else {
            int portIndex = 0;
            for (TupleTag<?> tag : transform.getSideOutputTags().getAll()) {
                if (tag.equals(output.getTag())) {
                    ports.put(pc, operator.sideOutputPorts[portIndex]);
                    break;
                }
                portIndex++;
            }
        }
    }
    context.addOperator(operator, ports);
    context.addStream(context.getInput(), operator.input);
    if (!sideInputs.isEmpty()) {
        addSideInputs(operator, sideInputs, context);
    }
}

From source file:com.github.jsdossier.soy.ProtoMessageSoyType.java

static SoyValue toSoyValue(GeneratedMessage message) {
    ProtoMessageSoyType type = ProtoMessageSoyType.get(message.getDescriptorForType());

    Map<String, Object> data = Maps.newHashMapWithExpectedSize(type.fieldDescriptors.size());
    for (Map.Entry<String, FieldDescriptor> entry : type.fieldDescriptors.entrySet()) {
        data.put(entry.getKey(), toSoyValue(entry.getValue(), message));
    }// w  w  w. j  a  v  a 2 s. c o  m
    return new SoyMapData(data);
}

From source file:voldemort.store.serialized.SerializingStore.java

@Override
public Map<K, List<Versioned<V>>> getAll(Iterable<K> keys, Map<K, T> transforms) throws VoldemortException {
    StoreUtils.assertValidKeys(keys);/*from w ww.j  a  va  2s. c  om*/
    Map<ByteArray, K> byteKeyToKey = keysToBytes(keys);
    Map<ByteArray, List<Versioned<byte[]>>> storeResult = store.getAll(byteKeyToKey.keySet(),
            transformsToBytes(transforms));
    Map<K, List<Versioned<V>>> result = Maps.newHashMapWithExpectedSize(storeResult.size());
    for (Map.Entry<ByteArray, List<Versioned<byte[]>>> mapEntry : storeResult.entrySet()) {
        List<Versioned<V>> values = Lists.newArrayListWithExpectedSize(mapEntry.getValue().size());
        for (Versioned<byte[]> versioned : mapEntry.getValue())
            values.add(
                    new Versioned<V>(valueSerializer.toObject(versioned.getValue()), versioned.getVersion()));

        result.put(byteKeyToKey.get(mapEntry.getKey()), values);
    }
    return result;
}

From source file:org.eclipse.hawkbit.ui.management.footer.ManangementConfirmationWindowLayout.java

@Override
protected Map<String, ConfirmationTab> getConfirmationTabs() {
    final Map<String, ConfirmationTab> tabs = Maps.newHashMapWithExpectedSize(3);
    if (!managementUIState.getDeletedDistributionList().isEmpty()) {
        tabs.put(i18n.getMessage("caption.delete.dist.accordion.tab"), createDeletedDistributionTab());
    }/*from  w w w . j  a va2 s  . c o  m*/
    if (!managementUIState.getDeletedTargetList().isEmpty()) {
        tabs.put(i18n.getMessage("caption.delete.target.accordion.tab"), createDeletedTargetTab());
    }
    if (!managementUIState.getAssignedList().isEmpty()) {
        tabs.put(i18n.getMessage("caption.assign.dist.accordion.tab"), createAssignmentTab());
    }
    return tabs;
}

From source file:org.openscience.cdk.layout.CorrectGeometricConfiguration.java

/**
 * Adjust all double bond elements in the provided structure.
 *
 * @param container the structure to adjust
 * @param graph     the adjacency list representation of the structure
 * @throws IllegalArgumentException an atom had unset coordinates
 *///from w w w .ja v a  2s.  com
CorrectGeometricConfiguration(IAtomContainer container, int[][] graph) {
    this.container = container;
    this.graph = graph;
    this.visited = new boolean[graph.length];
    this.atomToIndex = Maps.newHashMapWithExpectedSize(container.getAtomCount());
    this.ringSearch = new RingSearch(container, graph);

    for (int i = 0; i < container.getAtomCount(); i++) {
        IAtom atom = container.getAtom(i);
        atomToIndex.put(atom, i);
        if (atom.getPoint2d() == null)
            throw new IllegalArgumentException("atom " + i + " had unset coordinates");
    }

    for (IStereoElement element : container.stereoElements()) {
        if (element instanceof IDoubleBondStereochemistry) {
            adjust((IDoubleBondStereochemistry) element);
        }
    }
}

From source file:io.smartspaces.workbench.project.builder.BaseProjectBuilder.java

/**
 * Write out the resource source map contained in the project build context.
 *
 * @param project//from w ww.  ja va  2s.c  om
 *          current build project
 * @param stagingDirectory
 *          destination directory for build output
 * @param context
 *          project context containing the resource source map
 */
protected void writeResourceMap(Project project, File stagingDirectory, ProjectTaskContext context) {
    File resourceMapFile = fileSupport.newFile(context.getBuildDirectory(),
            ActivityProject.FILENAME_RESOURCE_MAP);

    Map<String, Object> templateData = new HashMap<>();
    List<Map<String, String>> srcList = new ArrayList<>();
    templateData.put(TEMPLATE_SRC_LIST_KEY, srcList);

    String stagingPrefix = stagingDirectory.getAbsolutePath() + File.separatorChar;

    for (Map.Entry<File, File> sourceEntry : context.getResourceFileCollector().entrySet()) {
        Map<String, String> stringMap = Maps.newHashMapWithExpectedSize(1);
        String destPath = sourceEntry.getKey().getAbsolutePath();
        if (destPath.startsWith(stagingPrefix)) {
            destPath = destPath.substring(stagingPrefix.length());
        }
        stringMap.put(TEMPLATE_ENTRY_DST_KEY, destPath);
        stringMap.put(TEMPLATE_ENTRY_SRC_KEY, sourceEntry.getValue().getAbsolutePath());
        srcList.add(stringMap);
    }
    context.getWorkbenchTaskContext().getWorkbench().getTemplater().writeTemplate(templateData, resourceMapFile,
            ACTIVITY_RESOURCE_MAP_TEMPLATE);
}

From source file:com.opengamma.core.AbstractEHCachingSourceWithExternalBundle.java

@SuppressWarnings("unchecked")
@Override/*from   w ww.j  av a 2s. c o m*/
public Map<ExternalIdBundle, Collection<V>> getAll(final Collection<ExternalIdBundle> bundles,
        VersionCorrection versionCorrection) {
    ArgumentChecker.notNull(bundles, "bundles");
    ArgumentChecker.notNull(versionCorrection, "versionCorrection");
    if (versionCorrection.containsLatest()) {
        return getUnderlying().getAll(bundles, versionCorrection);
    }
    final Map<ExternalIdBundle, Collection<V>> results = Maps.newHashMapWithExpectedSize(bundles.size());
    final Collection<ExternalIdBundle> misses = new ArrayList<ExternalIdBundle>(bundles.size());
    final Map<ExternalIdBundle, Collection<UniqueId>> lookupBundles = Maps
            .newHashMapWithExpectedSize(bundles.size());
    final Set<UniqueId> lookupIds = Sets.newHashSetWithExpectedSize(bundles.size());
    for (ExternalIdBundle bundle : bundles) {
        final Pair<ExternalIdBundle, VersionCorrection> key = Pair.of(bundle, versionCorrection);
        final Element e = _eidToUidCache.get(key);
        if (e != null) {
            if (e.getObjectValue() instanceof Collection) {
                final Collection<UniqueId> identifiers = (Collection<UniqueId>) e.getObjectValue();
                if (identifiers.isEmpty()) {
                    results.put(bundle, Collections.<V>emptySet());
                } else {
                    lookupBundles.put(bundle, identifiers);
                    lookupIds.addAll(identifiers);
                }
                continue;
            }
        }
        misses.add(bundle);
    }
    if (!lookupIds.isEmpty()) {
        final Map<UniqueId, V> underlying = get(lookupIds);
        for (Map.Entry<ExternalIdBundle, Collection<UniqueId>> lookupBundle : lookupBundles.entrySet()) {
            final ArrayList<V> resultCollection = new ArrayList<V>(lookupBundle.getValue().size());
            for (UniqueId uid : lookupBundle.getValue()) {
                final V resultValue = underlying.get(uid);
                if (resultValue != null) {
                    resultCollection.add(resultValue);
                }
            }
            resultCollection.trimToSize();
            results.put(lookupBundle.getKey(), resultCollection);
        }
    }
    if (!misses.isEmpty()) {
        final Map<ExternalIdBundle, Collection<V>> underlying = getUnderlying().getAll(misses,
                versionCorrection);
        for (ExternalIdBundle miss : misses) {
            final Pair<ExternalIdBundle, VersionCorrection> key = Pair.of(miss, versionCorrection);
            final Collection<V> result = underlying.get(miss);
            if ((result == null) || result.isEmpty()) {
                cacheIdentifiers(Collections.<UniqueId>emptyList(), key);
            } else {
                final List<UniqueId> uids = new ArrayList<UniqueId>(result.size());
                for (final V item : result) {
                    uids.add(item.getUniqueId());
                }
                Collections.sort(uids);
                cacheIdentifiers(uids, key);
                cacheItems(result);
                results.put(miss, result);
            }
        }
    }
    return results;
}

From source file:org.elasticsearch.action.search.TransportSearchHelper.java

static ParsedScrollId parseScrollId(String scrollId) {
    CharsRefBuilder spare = new CharsRefBuilder();
    try {//from   ww  w  .  jav  a 2 s.co m
        byte[] decode = Base64.decode(scrollId, Base64.URL_SAFE);
        spare.copyUTF8Bytes(decode, 0, decode.length);
    } catch (Exception e) {
        throw new IllegalArgumentException("Failed to decode scrollId", e);
    }
    String[] elements = Strings.splitStringToArray(spare.get(), ';');
    if (elements.length < 2) {
        throw new IllegalArgumentException("Malformed scrollId [" + scrollId + "]");
    }

    int index = 0;
    String type = elements[index++];
    int contextSize = Integer.parseInt(elements[index++]);
    if (elements.length < contextSize + 2) {
        throw new IllegalArgumentException("Malformed scrollId [" + scrollId + "]");
    }

    ScrollIdForNode[] context = new ScrollIdForNode[contextSize];
    for (int i = 0; i < contextSize; i++) {
        String element = elements[index++];
        int sep = element.indexOf(':');
        if (sep == -1) {
            throw new IllegalArgumentException("Malformed scrollId [" + scrollId + "]");
        }
        context[i] = new ScrollIdForNode(element.substring(sep + 1), Long.parseLong(element.substring(0, sep)));
    }
    Map<String, String> attributes;
    int attributesSize = Integer.parseInt(elements[index++]);
    if (attributesSize == 0) {
        attributes = ImmutableMap.of();
    } else {
        attributes = Maps.newHashMapWithExpectedSize(attributesSize);
        for (int i = 0; i < attributesSize; i++) {
            String element = elements[index++];
            int sep = element.indexOf(':');
            attributes.put(element.substring(0, sep), element.substring(sep + 1));
        }
    }
    return new ParsedScrollId(scrollId, type, context, attributes);
}

From source file:org.openscience.cdk.aromaticity.DaylightModel.java

/** @inheritDoc */
@Override//from   www  .j a va2s . co m
int[] contribution(IAtomContainer container, RingSearch ringSearch) {

    int n = container.getAtomCount();

    // we compute values we need for all atoms and then make the decisions
    // - this avoids costly operations such as looking up connected
    // bonds on each atom at the cost of memory
    int[] degree = new int[n];
    int[] bondOrderSum = new int[n];
    int[] nCyclicPiBonds = new int[n];
    int[] exocyclicPiBond = new int[n];
    int[] electrons = new int[n];

    Arrays.fill(exocyclicPiBond, -1);

    // index atoms and set the degree to the number of implicit hydrogens
    Map<IAtom, Integer> atomIndex = Maps.newHashMapWithExpectedSize(n);
    for (int i = 0; i < n; i++) {
        IAtom a = container.getAtom(i);
        atomIndex.put(a, i);
        degree[i] = checkNotNull(a.getImplicitHydrogenCount(),
                "Aromaticity model requires implicit hydrogen count is set.");
    }

    // for each bond we increase the degree count and check for cyclic and
    // exocyclic pi bonds. if there is a cyclic pi bond the atom is marked.
    // if there is an exocyclic pi bond we store the adjacent atom for
    // lookup later.
    for (IBond bond : container.bonds()) {
        int u = atomIndex.get(bond.getAtom(0));
        int v = atomIndex.get(bond.getAtom(1));
        degree[u]++;
        degree[v]++;

        IBond.Order order = checkNotNull(bond.getOrder(),
                "Aromaticity model requires that bond orders must be set");

        switch (order) {
        case UNSET:
            throw new IllegalArgumentException("Aromaticity model requires that bond orders must be set");
        case DOUBLE:
            if (ringSearch.cyclic(u, v)) {
                nCyclicPiBonds[u]++;
                nCyclicPiBonds[v]++;
            } else {
                exocyclicPiBond[u] = v;
                exocyclicPiBond[v] = u;
            }
            // note - fall through
        case SINGLE:
        case TRIPLE:
        case QUADRUPLE:
            bondOrderSum[u] += order.numeric();
            bondOrderSum[v] += order.numeric();
        }
    }

    // now make a decision on how many electrons each atom contributes
    for (int i = 0; i < n; i++) {

        int element = element(container.getAtom(i));
        int charge = charge(container.getAtom(i));

        // abnormal valence, usually indicated a radical. these cause problems
        // with kekulisations
        int bondedValence = bondOrderSum[i] + container.getAtom(i).getImplicitHydrogenCount();
        if (!normal(element, charge, bondedValence)) {
            electrons[i] = -1;
        }

        // non-aromatic element, acyclic atoms, atoms with more than three
        // neighbors and atoms with more than 1 cyclic pi bond are not
        // considered
        else if (!aromaticElement(element) || !ringSearch.cyclic(i) || degree[i] > 3 || nCyclicPiBonds[i] > 1) {
            electrons[i] = -1;
        }

        // exocyclic bond contributes 0 or 1 electrons depending on
        // preset electronegativity - check the exocyclicContribution method
        else if (exocyclicPiBond[i] >= 0) {
            electrons[i] = exocyclicContribution(element, element(container.getAtom(exocyclicPiBond[i])),
                    charge, nCyclicPiBonds[i]);
        }

        // any atom (except arsenic) with one cyclic pi bond contributes a
        // single electron
        else if (nCyclicPiBonds[i] == 1) {
            electrons[i] = element == ARSENIC ? -1 : 1;
        }

        // a anion with a lone pair contributes 2 electrons - simplification
        // here is we count the number free valence electrons but also
        // check if the bonded valence is okay (i.e. not a radical)
        else if (charge <= 0 && charge > -3) {
            if (valence(element, charge) - bondOrderSum[i] >= 2)
                electrons[i] = 2;
            else
                electrons[i] = -1;
        }

        else {
            // cation with no double bonds - single exception?
            if (element == CARBON && charge > 0)
                electrons[i] = 0;
            else
                electrons[i] = -1;
        }
    }

    return electrons;
}