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:com.android.tools.idea.wizard.ModuleListModel.java

private Multimap<ModuleToImport, ModuleToImport> computeRequiredModules(Set<ModuleToImport> modules) {
    Map<String, ModuleToImport> namesToModules = Maps.newHashMapWithExpectedSize(modules.size());
    // We only care about modules we are actually going to import.
    for (ModuleToImport module : modules) {
        namesToModules.put(module.name, module);
    }//from ww w.  j a  v a  2s.  co m
    Multimap<ModuleToImport, ModuleToImport> requiredModules = LinkedListMultimap.create();
    Queue<ModuleToImport> queue = Lists.newLinkedList();

    for (ModuleToImport module : modules) {
        if (Objects.equal(module, myPrimaryModule) || !isUnselected(module, false)) {
            queue.add(module);
        }
    }
    while (!queue.isEmpty()) {
        ModuleToImport moduleToImport = queue.remove();
        for (ModuleToImport dep : Iterables.transform(moduleToImport.getDependencies(),
                Functions.forMap(namesToModules, null))) {
            if (dep != null) {
                if (!requiredModules.containsKey(dep)) {
                    queue.add(dep);
                }
                requiredModules.put(dep, moduleToImport);
            }
        }
    }
    return requiredModules;
}

From source file:com.vityuk.ginger.DefaultLocalization.java

private <T extends Localizable> T createLocalizableInstance(Class<T> localizable) {
    Method[] methods = localizable.getDeclaredMethods();

    List<Callback> callbacks = Lists.newArrayListWithCapacity(methods.length + 1);
    final Map<Method, Integer> method2CallbackIndex = Maps.newHashMapWithExpectedSize(methods.length);

    callbacks.add(NoOp.INSTANCE);//  w w  w  .  j a  va  2  s.  co  m
    for (Method localizableMethod : methods) {
        callbacks.add(createCallback(localizableMethod));
        method2CallbackIndex.put(localizableMethod, callbacks.size() - 1);
    }

    CallbackFilter callbackFilter = new CallbackFilter() {
        @Override
        public int accept(Method method) {
            Integer index = method2CallbackIndex.get(method);
            return index == null ? 0 : index;
        }
    };

    T instance = createProxy(localizable, callbackFilter, callbacks);
    return instance;
}

From source file:io.druid.segment.MapVirtualColumn.java

@Override
public ColumnValueSelector<?> makeColumnValueSelector(String columnName, ColumnSelectorFactory factory) {
    final DimensionSelector keySelector = factory.makeDimensionSelector(DefaultDimensionSpec.of(keyDimension));
    final DimensionSelector valueSelector = factory
            .makeDimensionSelector(DefaultDimensionSpec.of(valueDimension));

    final String subColumnName = VirtualColumns.splitColumnName(columnName).rhs;

    if (subColumnName == null) {
        return new MapVirtualColumnValueSelector<Map>(keySelector, valueSelector) {
            @Override//from w ww. j  a v  a2 s  .com
            public Class<Map> classOfObject() {
                return Map.class;
            }

            @Override
            public Map getObject() {
                final IndexedInts keyIndices = keySelector.getRow();
                final IndexedInts valueIndices = valueSelector.getRow();
                final int limit = Math.min(keyIndices.size(), valueIndices.size());
                final Map<String, String> map = Maps.newHashMapWithExpectedSize(limit);
                for (int i = 0; i < limit; i++) {
                    map.put(keySelector.lookupName(keyIndices.get(i)),
                            valueSelector.lookupName(valueIndices.get(i)));
                }
                return map;
            }
        };
    }

    IdLookup keyIdLookup = keySelector.idLookup();
    if (keyIdLookup != null) {
        final int keyId = keyIdLookup.lookupId(subColumnName);
        if (keyId < 0) {
            return NilColumnValueSelector.instance();
        }
        return new MapVirtualColumnValueSelector<String>(keySelector, valueSelector) {
            @Override
            public Class<String> classOfObject() {
                return String.class;
            }

            @Nullable
            @Override
            public String getObject() {
                final IndexedInts keyIndices = keySelector.getRow();
                final IndexedInts valueIndices = valueSelector.getRow();
                final int limit = Math.min(keyIndices.size(), valueIndices.size());
                for (int i = 0; i < limit; i++) {
                    if (keyIndices.get(i) == keyId) {
                        return valueSelector.lookupName(valueIndices.get(i));
                    }
                }
                return null;
            }
        };
    } else {
        return new MapVirtualColumnValueSelector<String>(keySelector, valueSelector) {
            @Override
            public Class<String> classOfObject() {
                return String.class;
            }

            @Nullable
            @Override
            public String getObject() {
                final IndexedInts keyIndices = keySelector.getRow();
                final IndexedInts valueIndices = valueSelector.getRow();
                final int limit = Math.min(keyIndices.size(), valueIndices.size());
                for (int i = 0; i < limit; i++) {
                    if (Objects.equals(keySelector.lookupName(keyIndices.get(i)), subColumnName)) {
                        return valueSelector.lookupName(valueIndices.get(i));
                    }
                }
                return null;
            }
        };
    }
}

From source file:cosmos.records.impl.MapRecord.java

@Override
public void readFields(DataInput in) throws IOException {
    this.docId = Text.readString(in);

    final int cvLength = WritableUtils.readVInt(in);
    final byte[] cvBytes = new byte[cvLength];
    in.readFully(cvBytes);//from w w  w . ja va2s .  c  o m

    this.docVisibility = new ColumnVisibility(cvBytes);

    final int entryCount = WritableUtils.readVInt(in);
    this.document = Maps.newHashMapWithExpectedSize(entryCount);

    for (int i = 0; i < entryCount; i++) {

        this.document.put(Column.recreate(in), RecordValue.recreate(in));
    }
}

From source file:com.google.gitiles.CommitSoyData.java

public Map<String, Object> toSoyData(RevCommit commit, KeySet keys) throws IOException {
    Map<String, Object> data = Maps.newHashMapWithExpectedSize(KeySet.DEFAULT.keys.size());
    if (keys.keys.contains("author")) {
        data.put("author", toSoyData(commit.getAuthorIdent(), dateFormatter));
    }//from   w  w w  . j a v a2 s.  c  o m
    if (keys.keys.contains("committer")) {
        data.put("committer", toSoyData(commit.getCommitterIdent(), dateFormatter));
    }
    if (keys.keys.contains("sha")) {
        data.put("sha", ObjectId.toString(commit));
    }
    if (keys.keys.contains("abbrevSha")) {
        ObjectReader reader = repo.getObjectDatabase().newReader();
        try {
            data.put("abbrevSha", reader.abbreviate(commit).name());
        } finally {
            reader.release();
        }
    }
    if (keys.keys.contains("url")) {
        data.put("url", GitilesView.revision().copyFrom(view).setRevision(commit).toUrl());
    }
    if (keys.keys.contains("logUrl")) {
        Revision rev = view.getRevision();
        GitilesView.Builder logView = GitilesView.log().copyFrom(view)
                .setRevision(rev.getId().equals(commit) ? rev.getName() : commit.name(), commit)
                .setOldRevision(Revision.NULL).setTreePath(null);
        data.put("logUrl", logView.toUrl());
    }
    if (keys.keys.contains("tree")) {
        data.put("tree", ObjectId.toString(commit.getTree()));
    }
    if (keys.keys.contains("treeUrl")) {
        data.put("treeUrl", GitilesView.path().copyFrom(view).setTreePath("/").toUrl());
    }
    if (keys.keys.contains("parents")) {
        data.put("parents", toSoyData(view, commit.getParents()));
    }
    if (keys.keys.contains("shortMessage")) {
        data.put("shortMessage", commit.getShortMessage());
    }
    if (keys.keys.contains("branches")) {
        data.put("branches", getRefsById(commit, Constants.R_HEADS));
    }
    if (keys.keys.contains("tags")) {
        data.put("tags", getRefsById(commit, Constants.R_TAGS));
    }
    if (keys.keys.contains("message")) {
        if (linkifier != null) {
            data.put("message", linkifier.linkify(req, commit.getFullMessage()));
        } else {
            data.put("message", commit.getFullMessage());
        }
    }
    if (keys.keys.contains("diffTree")) {
        data.put("diffTree", computeDiffTree(commit));
    }
    checkState(keys.keys.size() == data.size(), "bad commit data keys: %s != %s", keys.keys, data.keySet());
    return ImmutableMap.copyOf(data);
}

From source file:org.eclipse.hawkbit.api.PropertyBasedArtifactUrlHandler.java

private static Map<String, String> getReplaceMap(final UrlProtocol protocol, final URLPlaceholder placeholder,
        final URI requestUri) {
    final Map<String, String> replaceMap = Maps.newHashMapWithExpectedSize(19);
    replaceMap.put(IP_PLACEHOLDER, protocol.getIp());
    replaceMap.put(HOSTNAME_PLACEHOLDER, protocol.getHostname());

    replaceMap.put(HOSTNAME_REQUEST_PLACEHOLDER, getRequestHost(protocol, requestUri));
    replaceMap.put(PORT_REQUEST_PLACEHOLDER, getRequestPort(protocol, requestUri));
    replaceMap.put(HOSTNAME_WITH_DOMAIN_REQUEST_PLACEHOLDER,
            computeHostWithRequestDomain(protocol, requestUri));

    replaceMap.put(ARTIFACT_FILENAME_PLACEHOLDER,
            UrlEscapers.urlFragmentEscaper().escape(placeholder.getSoftwareData().getFilename()));
    replaceMap.put(ARTIFACT_SHA1_PLACEHOLDER, placeholder.getSoftwareData().getSha1Hash());
    replaceMap.put(PROTOCOL_PLACEHOLDER, protocol.getProtocol());
    replaceMap.put(PORT_PLACEHOLDER, getPort(protocol));
    replaceMap.put(TENANT_PLACEHOLDER, placeholder.getTenant());
    replaceMap.put(TENANT_ID_BASE10_PLACEHOLDER, String.valueOf(placeholder.getTenantId()));
    replaceMap.put(TENANT_ID_BASE62_PLACEHOLDER, Base62Util.fromBase10(placeholder.getTenantId()));
    replaceMap.put(CONTROLLER_ID_PLACEHOLDER, placeholder.getControllerId());
    replaceMap.put(TARGET_ID_BASE10_PLACEHOLDER, String.valueOf(placeholder.getTargetId()));
    replaceMap.put(TARGET_ID_BASE62_PLACEHOLDER, Base62Util.fromBase10(placeholder.getTargetId()));
    replaceMap.put(ARTIFACT_ID_BASE62_PLACEHOLDER,
            Base62Util.fromBase10(placeholder.getSoftwareData().getArtifactId()));
    replaceMap.put(ARTIFACT_ID_BASE10_PLACEHOLDER,
            String.valueOf(placeholder.getSoftwareData().getArtifactId()));
    replaceMap.put(SOFTWARE_MODULE_ID_BASE10_PLACDEHOLDER,
            String.valueOf(placeholder.getSoftwareData().getSoftwareModuleId()));
    replaceMap.put(SOFTWARE_MODULE_ID_BASE62_PLACDEHOLDER,
            Base62Util.fromBase10(placeholder.getSoftwareData().getSoftwareModuleId()));
    return replaceMap;
}

From source file:abstractions.piece.PieceSetFactory.java

public <T extends Enum<T> & PieceTypeInterface> Map<SideInterface, Set<PieceInterface>> newPieceSet(
        final Class<T> pieceTypeSetClass) {

    final Set<T> pieceTypeSet = Sets.newHashSet(pieceTypeSetClass.getEnumConstants());

    if (pieceTypeSet.isEmpty()) {
        throw new IllegalPieceSetException("Set of pieces '" + pieceTypeSetClass.getSimpleName()
                + "' must contain the NULL piece type and at least one not-NULL piece type.");
    }//from ww  w.j ava2s.  c o  m

    final Iterator<T> piecesAlphabetIterator = pieceTypeSet.iterator();
    T nullType = null;
    try {
        while (!(nullType = piecesAlphabetIterator.next()).name().equalsIgnoreCase("null")) { // NOPMD
            ;
        }
    } catch (final NoSuchElementException e) {
        throw new IllegalPieceSetException(
                "Set of pieces '" + pieceTypeSetClass.getSimpleName() + "' must contain the NULL piece type."); // NOPMD
    }
    pieceTypeSet.remove(nullType);

    if (pieceTypeSet.isEmpty()) {
        throw new IllegalPieceSetException("Set of pieces '" + pieceTypeSetClass.getSimpleName()
                + "' must contain at least one not-NULL piece type.");
    }

    final String path = pieceTypeSetClass.getPackage().getName();

    final Map<SideInterface, Set<PieceInterface>> piecesMap = Maps.newHashMapWithExpectedSize(3);

    final Set<PieceInterface> nullPiece = Sets.newHashSet(this.newPiece(path, nullType, Sides.NULL));
    piecesMap.put(Sides.NULL, nullPiece);

    final Set<PieceInterface> firstSidePieces = Sets.newHashSetWithExpectedSize(pieceTypeSet.size());
    for (final PieceTypeInterface pieceType : pieceTypeSet) {
        firstSidePieces.add(this.newPiece(path, pieceType, Sides.FIRST));
    }
    piecesMap.put(Sides.FIRST, firstSidePieces);

    final Set<PieceInterface> secondSidePieces = Sets.newHashSetWithExpectedSize(pieceTypeSet.size());
    for (final PieceTypeInterface pieceType : pieceTypeSet) {
        secondSidePieces.add(this.newPiece(path, pieceType, Sides.SECOND));
    }
    piecesMap.put(Sides.SECOND, secondSidePieces);

    return Collections.unmodifiableMap(piecesMap);
}

From source file:com.vityuk.ginger.loader.PropertiesLocalizationLoader.java

private ResourcePropertyResolver load(MatchingReader reader) throws IOException {
    final Map<String, String> properties = Maps.newHashMap();
    final Map<String, Map<String, String>> mapProperties = Maps.newHashMap();

    while (!reader.isEndOfStream()) {
        int code = reader.peek();
        if (COMMENT_MATCHER.matches((char) code)) {
            reader.skipCharacters(NOT_LINE_SEPARATOR_MATCHER);
            continue;
        }//ww  w. j  a  v  a  2 s .  c om

        reader.skipCharacters(WHITESPACE_MATCHER);
        if (!reader.isEndOfLine()) {
            String key = reader.readLineUntil(WHITESPACE_OR_SEPARATOR_MATCHER);

            reader.skipCharacters(WHITESPACE_MATCHER);

            code = reader.peek();
            if (code != -1 && KEY_VALUE_SEPARATOR_MATCHER.matches((char) code)) {
                reader.read();
                reader.skipCharacters(WHITESPACE_MATCHER);
            }

            String value = reader.readLineUntil(LINE_SEPARATOR_MATCHER);

            Matcher matcher = MAP_KEY_PATTERN.matcher(key);
            if (matcher.matches()) {
                /*
                 This is map property of format: propertyKey[mapKey]=value
                */
                String propertyKey = matcher.group(1);
                String mapKey = matcher.group(2);
                Map<String, String> propertyMap = mapProperties.get(propertyKey);
                if (propertyMap == null) {
                    propertyMap = Maps.newHashMapWithExpectedSize(4);
                    mapProperties.put(propertyKey, propertyMap);
                }
                propertyMap.put(mapKey, value);
            } else {
                properties.put(key, value);
            }
        }
        reader.skipCharacters(LINE_SEPARATOR_MATCHER);
    }

    return new ResourcePropertyResolver(properties, mapProperties);
}

From source file:com.android.tools.idea.rendering.LayoutFilePullParser.java

@Override
@Nullable/*  ww w .  j  a v a 2  s .  com*/
public Object getViewCookie() {
    String name = super.getName();
    if (name == null) {
        return null;
    }

    // Store tools attributes if this looks like a layout we'll need adapter view
    // bindings for in the LayoutlibCallback.
    if (LIST_VIEW.equals(name) || EXPANDABLE_LIST_VIEW.equals(name) || GRID_VIEW.equals(name)
            || SPINNER.equals(name)) {
        Map<String, String> map = null;
        int count = getAttributeCount();
        for (int i = 0; i < count; i++) {
            String namespace = getAttributeNamespace(i);
            if (namespace != null && namespace.equals(TOOLS_URI)) {
                String attribute = getAttributeName(i);
                if (attribute.equals(ATTR_IGNORE)) {
                    continue;
                }
                if (map == null) {
                    map = Maps.newHashMapWithExpectedSize(4);
                }
                map.put(attribute, getAttributeValue(i));
            }
        }

        return map;
    }

    return null;
}

From source file:com.opengamma.engine.view.compilation.SubGraphingFilter.java

/**
 * Creates a sub-graph of this graph. If the filter would accept all of the nodes, the original graph is returned unchanged.
 * // w w  w. ja v  a2 s .c o  m
 * @param graph the graph to filter, not null
 * @param missingRequirements receives the original value requirements whose resolved value specifications were removed from the graph
 * @return the filtered graph, not null
 */
public DependencyGraph subGraph(final DependencyGraph graph, final Set<ValueRequirement> missingRequirements) {
    final Collection<DependencyNode> nodes = graph.getDependencyNodes();
    final int size = nodes.size();
    if ((_include == null) || (_include.size() < size)) {
        _include = Maps.newHashMapWithExpectedSize(size);
    } else {
        _include.clear();
    }
    if (areIncluded(nodes)) {
        return graph;
    } else {
        _terminalOutputs = graph.getTerminalOutputs();
        _missingRequirements = missingRequirements;
        return graph.subGraph(this);
    }
}