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.pinterest.terrapin.controller.TerrapinRoutingTableProvider.java

public TerrapinRoutingTableProvider(ZooKeeperManager zkManager, List<String> resourceList) {
    this.zkManager = zkManager;
    this.viewInfoRecordMap = Maps.newHashMapWithExpectedSize(resourceList.size());
    // Initialize the view info with what we have in zookeeper to avoid double writes.
    for (String resource : resourceList) {
        ViewInfo viewInfo = this.zkManager.getViewInfo(resource);
        if (viewInfo != null) {
            ViewInfoRecord viewInfoRecord = new ViewInfoRecord();
            viewInfoRecord.drained = true;
            viewInfoRecord.viewInfo = viewInfo;
            this.viewInfoRecordMap.put(resource, viewInfoRecord);
        } else {//from  w  ww  .  j a  v a2 s .  com
            LOG.error("Compressed view is null on startup for " + resource);
            Stats.incr("compressed-view-init-errors");
        }
    }
}

From source file:org.sosy_lab.cpachecker.util.reachingdef.ReachingDefinitionStorage.java

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    int numElem, numKeys, numPoints;
    String key;/*w w w. j ava  2 s. c  om*/
    DefinitionPoint[] set;
    Map<String, Set<DefinitionPoint>> map;

    numElem = in.readInt();
    savedReachingDefinitions = new ArrayList<>(numElem);

    for (int i = 0; i < numElem; i++) {
        numKeys = in.readInt();

        map = Maps.newHashMapWithExpectedSize(numKeys);
        for (int j = 0; j < numKeys; j++) {
            key = (String) in.readObject();

            numPoints = in.readInt();
            set = new DefinitionPoint[numPoints];
            for (int k = 0; k < numPoints; k++) {
                set[k] = (DefinitionPoint) in.readObject();
            }

            map.put(key, ImmutableSet.copyOf(set));

        }
        savedReachingDefinitions.add(map);
    }
    instance.savedReachingDefinitions = savedReachingDefinitions;
}

From source file:gg.uhc.uhc.modules.death.DeathStandsModule.java

@SuppressWarnings("Duplicates")
protected Map<EquipmentSlot, ItemStack> getItems(PlayerInventory inventory) {
    Map<EquipmentSlot, ItemStack> slots = Maps.newHashMapWithExpectedSize(5);

    slots.put(EquipmentSlot.HAND, inventory.getItemInHand());
    slots.put(EquipmentSlot.HEAD, inventory.getHelmet());
    slots.put(EquipmentSlot.CHEST, inventory.getChestplate());
    slots.put(EquipmentSlot.LEGS, inventory.getLeggings());
    slots.put(EquipmentSlot.FEET, inventory.getBoots());

    return slots;
}

From source file:com.opengamma.engine.target.resolver.AbstractIdentifierResolver.java

public static Map<ObjectId, UniqueId> resolveObjectIdsSingleThread(final IdentifierResolver resolver,
        final Collection<ObjectId> identifiers, final VersionCorrection versionCorrection) {
    final Map<ObjectId, UniqueId> result = Maps.newHashMapWithExpectedSize(identifiers.size());
    for (final ObjectId identifier : identifiers) {
        final UniqueId uid = resolver.resolveObjectId(identifier, versionCorrection);
        if (uid != null) {
            result.put(identifier, uid);
        }//from   www. j a  v  a  2  s  .c  o m
    }
    return result;
}

From source file:com.opengamma.engine.marketdata.MarketDataSnapshotWithOverride.java

@Override
public Map<ValueSpecification, Object> query(final Set<ValueSpecification> values) {
    if (getOverride() != null) {
        final Set<ValueSpecification> unresolved = new HashSet<ValueSpecification>(values);
        final Map<ValueSpecification, Object> result = Maps.newHashMapWithExpectedSize(values.size());
        final Map<ValueSpecification, OverrideOperation> overrideOperations = Maps
                .newHashMapWithExpectedSize(values.size());
        for (ValueSpecification value : values) {
            Object response = getOverride().query(value);
            if (response == null) {
                continue;
            } else if (response instanceof OverrideOperation) {
                overrideOperations.put(value, (OverrideOperation) response);
            } else {
                result.put(value, response);
                unresolved.remove(value);
            }//from  w w w.j ava  2  s  .  com
        }
        if (!unresolved.isEmpty()) {
            final Map<ValueSpecification, Object> response = getUnderlying().query(unresolved);
            if (response != null) {
                for (final Map.Entry<ValueSpecification, Object> underlyingEntry : response.entrySet()) {
                    final OverrideOperation overrideOperation = overrideOperations
                            .get(underlyingEntry.getKey());
                    if (overrideOperation != null) {
                        result.put(underlyingEntry.getKey(),
                                overrideOperation.apply(getOverrideValueRequirement(underlyingEntry.getKey()),
                                        underlyingEntry.getValue()));
                    } else {
                        result.put(underlyingEntry.getKey(), underlyingEntry.getValue());
                    }
                }
            }
        }
        return result;
    } else {
        return getUnderlying().query(values);
    }
}

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

/** @inheritDoc */
@Override/*from ww w  . ja  v  a  2  s.  c  o m*/
int[] contribution(IAtomContainer container, RingSearch ringSearch) {

    final int nAtoms = container.getAtomCount();
    final int[] electrons = new int[nAtoms];

    Arrays.fill(electrons, -1);

    final Map<IAtom, Integer> indexMap = Maps.newHashMapWithExpectedSize(nAtoms);

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

        IAtom atom = container.getAtom(i);
        indexMap.put(atom, i);

        // acyclic atom skipped
        if (!ringSearch.cyclic(i))
            continue;

        Hybridization hyb = atom.getHybridization();

        checkNotNull(atom.getAtomTypeName(), "atom has unset atom type");

        // atom has been assigned an atom type but we don't know the hybrid state,
        // typically for atom type 'X' (unknown)
        if (hyb == null)
            continue;

        switch (hyb) {
        case SP2:
        case PLANAR3:
            electrons[i] = electronsForAtomType(atom);
            break;
        case SP3:
            electrons[i] = lonePairCount(atom) > 0 ? 2 : -1;
            break;
        }
    }

    // exocyclic double bonds are allowed no further processing
    if (exocyclic)
        return electrons;

    // check for exocyclic double/triple bonds and disallow their contribution
    for (IBond bond : container.bonds()) {
        if (bond.getOrder() == IBond.Order.DOUBLE || bond.getOrder() == IBond.Order.TRIPLE) {

            IAtom a1 = bond.getAtom(0);
            IAtom a2 = bond.getAtom(1);

            String a1Type = a1.getAtomTypeName();
            String a2Type = a2.getAtomTypeName();

            int u = indexMap.get(a1);
            int v = indexMap.get(a2);

            if (!ringSearch.cyclic(u, v)) {

                // XXX: single exception - we could make this more general but
                // for now this mirrors the existing behavior
                if (a1Type.equals("N.sp2.3") && a2Type.equals("O.sp2")
                        || a1Type.equals("O.sp2") && a2Type.equals("N.sp2.3"))
                    continue;

                electrons[u] = electrons[v] = -1;
            }
        }
    }

    return electrons;
}

From source file:org.sosy_lab.cpachecker.pcc.strategy.BackwardTargetsReachedSetStrategy.java

private AbstractState[] detectBackwardTargets(final ARGState rootNode, final int size) {
    // DFS to detect circles (backward targets)
    Collection<AbstractState> statesToStore = new HashSet<>();
    Map<ARGState, Pair<Integer, Integer>> exploreTimes = Maps.newHashMapWithExpectedSize(size);
    Deque<Pair<ARGState, Iterator<ARGState>>> toVisit = new ArrayDeque<>();

    int time = 0;
    exploreTimes.put(rootNode, Pair.of(time++, Integer.MAX_VALUE));
    toVisit.add(Pair.of(rootNode, rootNode.getChildren().iterator()));
    Pair<ARGState, Iterator<ARGState>> top;
    Pair<Integer, Integer> exploreTime;
    ARGState uncoveredChild;/* w w  w .  j av a  2 s.c  o  m*/

    while (!toVisit.isEmpty()) {
        top = toVisit.peek();

        if (!top.getSecond().hasNext()) {
            exploreTimes.put(top.getFirst(), Pair.of(exploreTimes.get(top.getFirst()).getFirst(), time++));
            toVisit.pop();
            continue;
        }

        uncoveredChild = replaceByCoveringState(top.getSecond().next());
        if (exploreTimes.containsKey(uncoveredChild)) {
            exploreTime = exploreTimes.get(uncoveredChild);
            if (exploreTime.getFirst() < time && exploreTime.getSecond() > time) {
                if (certificateStatesAsARGStates) {
                    statesToStore.add(uncoveredChild);
                } else {
                    statesToStore.add(uncoveredChild.getWrappedState());
                }
            }
        } else {
            toVisit.push(Pair.of(uncoveredChild, uncoveredChild.getChildren().iterator()));
            exploreTimes.put(uncoveredChild, Pair.of(time++, Integer.MAX_VALUE));
        }
    }

    return statesToStore.toArray(new AbstractState[statesToStore.size()]);
}

From source file:org.apache.hadoop.hbase.index.util.IndexManagementUtil.java

public static ValueGetter createGetterFromKeyValues(Collection<KeyValue> pendingUpdates) {
    final Map<ReferencingColumn, ImmutableBytesPtr> valueMap = Maps
            .newHashMapWithExpectedSize(pendingUpdates.size());
    for (KeyValue kv : pendingUpdates) {
        // create new pointers to each part of the kv
        ImmutableBytesPtr family = new ImmutableBytesPtr(kv.getBuffer(), kv.getFamilyOffset(),
                kv.getFamilyLength());//w  ww. j  av a  2s  . c  o m
        ImmutableBytesPtr qual = new ImmutableBytesPtr(kv.getBuffer(), kv.getQualifierOffset(),
                kv.getQualifierLength());
        ImmutableBytesPtr value = new ImmutableBytesPtr(kv.getBuffer(), kv.getValueOffset(),
                kv.getValueLength());
        valueMap.put(new ReferencingColumn(family, qual), value);
    }
    return new ValueGetter() {
        @Override
        public ImmutableBytesPtr getLatestValue(ColumnReference ref) throws IOException {
            return valueMap.get(ReferencingColumn.wrap(ref));
        }
    };
}

From source file:org.apache.shindig.protocol.conversion.BeanFilter.java

@SuppressWarnings("unchecked")
private Object createFilteredBean(Object data, Set<String> fields, String fieldName) {
    // For null, atomic object or for all fields just return original.
    if (data == null || fields == null || BeanDelegator.PRIMITIVE_TYPE_CLASSES.contains(data.getClass())
            || fields.contains(ALL_FIELDS)) {
        return data;
    }/*from w  ww  .j  a  va 2s. c  o m*/

    // For map, generate a new map with filtered objects
    if (data instanceof Map<?, ?>) {
        Map<Object, Object> oldMap = (Map<Object, Object>) data;
        Map<Object, Object> newMap = Maps.newHashMapWithExpectedSize(oldMap.size());
        for (Map.Entry<Object, Object> entry : oldMap.entrySet()) {
            newMap.put(entry.getKey(), createFilteredBean(entry.getValue(), fields, fieldName));
        }
        return newMap;
    }

    // For list, generate a new list of filtered objects
    if (data instanceof List<?>) {
        List<Object> oldList = (List<Object>) data;
        List<Object> newList = Lists.newArrayListWithCapacity(oldList.size());
        for (Object entry : oldList) {
            newList.add(createFilteredBean(entry, fields, fieldName));
        }
        return newList;
    }

    // Create a new intercepted object:
    return Proxy.newProxyInstance(data.getClass().getClassLoader(), data.getClass().getInterfaces(),
            new FilterInvocationHandler(data, fields, fieldName));
}

From source file:io.divolte.server.recordmapping.DslRecordMapper.java

@Override
public GenericRecord newRecordFromExchange(HttpServerExchange exchange) {
    final GenericRecordBuilder builder = new GenericRecordBuilder(schema);
    final DivolteEvent eventData = exchange.getAttachment(DIVOLTE_EVENT_KEY);
    final Map<String, Optional<?>> context = Maps.newHashMapWithExpectedSize(20);

    for (final Iterator<MappingAction> itr = actions.iterator(); itr.hasNext()
            && itr.next().perform(exchange, eventData, context, builder) == MappingResult.CONTINUE;) {
        // Nothing needed in here.
    }/*from   w  ww  . j  a  v a  2 s  .  c o  m*/

    return builder.build();
}