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

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

Introduction

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

Prototype

public static <E> HashSet<E> newHashSetWithExpectedSize(int expectedSize) 

Source Link

Document

Creates a HashSet instance, with a high enough initial table size that it should hold expectedSize elements without resizing.

Usage

From source file:org.apache.bookkeeper.clients.impl.kv.PByteBufTableImpl.java

CompletableFuture<PTable<ByteBuf, ByteBuf>> refreshRangeSpaces(HashStreamRanges newRanges) {
    // compare the ranges to see if it requires an update
    HashStreamRanges oldRanges = rangeRouter.getRanges();
    if (null != oldRanges && oldRanges.getMaxRangeId() >= newRanges.getMaxRangeId()) {
        log.info("No new stream ranges found for stream {}.", streamName);
        return FutureUtils.value(this);
    }/*w  w w .  j a  va2s. co m*/
    if (log.isInfoEnabled()) {
        log.info("Updated the active ranges to {}", newRanges);
    }
    rangeRouter.setRanges(newRanges);
    // add new ranges
    Set<Long> activeRanges = Sets.newHashSetWithExpectedSize(newRanges.getRanges().size());
    newRanges.getRanges().forEach((rk, range) -> {
        activeRanges.add(range.getRangeId());
        if (tableRanges.containsKey(range.getRangeId())) {
            return;
        }
        PTable<ByteBuf, ByteBuf> tableRange = trFactory.openTableRange(props, range, executor, opFactory,
                resultFactory, kvFactory);
        if (log.isInfoEnabled()) {
            log.info("Create table range client for range {}", range.getRangeId());
        }
        this.tableRanges.put(range.getRangeId(), tableRange);
    });
    // remove old ranges
    Iterator<Entry<Long, PTable<ByteBuf, ByteBuf>>> rsIter = tableRanges.entrySet().iterator();
    while (rsIter.hasNext()) {
        Map.Entry<Long, PTable<ByteBuf, ByteBuf>> entry = rsIter.next();
        Long rid = entry.getKey();
        if (activeRanges.contains(rid)) {
            continue;
        }
        rsIter.remove();
        PTable oldRangeSpace = entry.getValue();
        oldRangeSpace.close();
    }
    return FutureUtils.value(this);
}

From source file:com.android.tools.idea.uibuilder.structure.NlComponentTree.java

@NotNull
private Collection<NlComponent> getCollapsedComponents() {
    int rowCount = getRowCount();
    Collection<NlComponent> components = Sets.newHashSetWithExpectedSize(rowCount);

    for (int row = 0; row < rowCount; row++) {
        if (isCollapsed(row)) {
            NlComponent component = (NlComponent) getPathForRow(row).getLastPathComponent();

            if (component.getChildCount() != 0) {
                components.add(component);
            }/*from w  ww.j  av a 2  s.co  m*/
        }
    }

    return components;
}

From source file:org.jalphanode.jmx.MBeanAnnotationScanner.java

private Set<Method> allAccessors(final BeanInfo beanInfo) {
    final PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
    final Set<Method> allAccessors = Sets.newHashSetWithExpectedSize(propertyDescriptors.length);

    for (PropertyDescriptor propertyDescriptor : propertyDescriptors) {
        Method getter = propertyDescriptor.getReadMethod();
        if (getter != null) {
            allAccessors.add(getter);/*  w  ww .  j  a  v a  2  s  .  com*/
        }

        Method setter = propertyDescriptor.getWriteMethod();
        if (setter != null) {
            allAccessors.add(setter);
        }
    }

    return allAccessors;
}

From source file:com.edmunds.etm.management.api.ManagementVip.java

/**
 * Creates a ManagementVip from the given DTO.
 *
 * @param dto   the DTO to read// w ww.j a  v a  2  s  .  c o m
 * @param state load balancer state of the new vip
 * @return a ManagementVip object
 */
public static ManagementVip readDto(ManagementVipDto dto, ManagementLoadBalancerState state) {
    if (dto == null) {
        return null;
    }
    MavenModule mavenModule = MavenModule.readDto(dto.getMavenModule());
    HostAddress vipAddress = HostAddress.readDto(dto.getHostAddress());
    HttpMonitor httpMonitor = HttpMonitor.readDto(dto.getHttpMonitor());
    String rootContext = dto.getContextPath();
    List<String> rules = dto.getUrlRules();

    Set<ManagementPoolMember> members = Sets.newHashSetWithExpectedSize(dto.getPoolMembersSize());
    for (ManagementPoolMemberDto memberDto : dto.getPoolMembers()) {
        members.add(ManagementPoolMember.readDto(memberDto, ACTIVE));
    }
    return new ManagementVip(state, mavenModule, vipAddress, members, rootContext, rules, httpMonitor);
}

From source file:com.android.tools.lint.checks.WrongIdDetector.java

@Override
public void afterCheckFile(@NonNull Context context) {
    if (mRelativeLayouts != null) {
        if (!context.getProject().getReportIssues()) {
            // If this is a library project not being analyzed, ignore it
            return;
        }//  w w  w. j  av  a 2  s  . c o  m

        for (Element layout : mRelativeLayouts) {
            List<Element> children = getChildren(layout);
            Set<String> ids = Sets.newHashSetWithExpectedSize(children.size());
            for (Element child : children) {
                String id = child.getAttributeNS(ANDROID_URI, ATTR_ID);
                if (id != null && !id.isEmpty()) {
                    ids.add(id);
                }
            }

            for (Element element : children) {
                String selfId = stripIdPrefix(element.getAttributeNS(ANDROID_URI, ATTR_ID));

                NamedNodeMap attributes = element.getAttributes();
                for (int i = 0, n = attributes.getLength(); i < n; i++) {
                    Attr attr = (Attr) attributes.item(i);
                    String value = attr.getValue();
                    if ((value.startsWith(NEW_ID_PREFIX) || value.startsWith(ID_PREFIX))
                            && ANDROID_URI.equals(attr.getNamespaceURI())
                            && attr.getLocalName().startsWith(ATTR_LAYOUT_RESOURCE_PREFIX)) {
                        if (!idDefined(mFileIds, value)) {
                            // Stash a reference to this id and location such that
                            // we can check after the *whole* layout has been processed,
                            // since it's too early to conclude here that the id does
                            // not exist (you are allowed to have forward references)
                            XmlContext xmlContext = (XmlContext) context;
                            Handle handle = xmlContext.createLocationHandle(attr);
                            handle.setClientData(attr);

                            if (mHandles == null) {
                                mHandles = new ArrayList<Pair<String, Handle>>();
                            }
                            mHandles.add(Pair.of(value, handle));
                        } else {
                            // Check siblings. TODO: Look for cycles!
                            if (ids.contains(value)) {
                                // Make sure it's not pointing to self
                                if (!ATTR_ID.equals(attr.getLocalName()) && !selfId.isEmpty()
                                        && value.endsWith(selfId) && stripIdPrefix(value).equals(selfId)) {
                                    XmlContext xmlContext = (XmlContext) context;
                                    String message = String.format(
                                            "Cannot be relative to self: id=%1$s, %2$s=%3$s", selfId,
                                            attr.getLocalName(), selfId);
                                    Location location = xmlContext.getLocation(attr);
                                    xmlContext.report(NOT_SIBLING, attr, location, message);
                                }

                                continue;
                            }
                            if (value.startsWith(NEW_ID_PREFIX)) {
                                if (ids.contains(ID_PREFIX + stripIdPrefix(value))) {
                                    continue;
                                }
                            } else {
                                assert value.startsWith(ID_PREFIX) : value;
                                if (ids.contains(NEW_ID_PREFIX + stripIdPrefix(value))) {
                                    continue;
                                }
                            }
                            if (context.isEnabled(NOT_SIBLING)) {
                                XmlContext xmlContext = (XmlContext) context;
                                String message = String
                                        .format("`%1$s` is not a sibling in the same `RelativeLayout`", value);
                                Location location = xmlContext.getLocation(attr);
                                xmlContext.report(NOT_SIBLING, attr, location, message);
                            }
                        }
                    }
                }
            }
        }
    }

    mFileIds = null;

    if (!context.getScope().contains(Scope.ALL_RESOURCE_FILES)) {
        checkHandles(context);
    }
}

From source file:com.opengamma.financial.analytics.model.equity.option.EquityVanillaBarrierOptionBlackFunction.java

@Override
public Set<ValueSpecification> getResults(final FunctionCompilationContext context,
        final ComputationTarget target, final Map<ValueSpecification, ValueRequirement> inputs) {
    final Set<ValueSpecification> results = super.getResults(context, target, inputs);
    final Set<ValueSpecification> resultsWithExtraProperties = Sets.newHashSetWithExpectedSize(results.size());
    for (final ValueSpecification spec : results) {
        final String name = spec.getValueName();
        final ComputationTargetSpecification targetSpec = spec.getTargetSpecification();
        final ValueProperties properties = spec.getProperties().copy()
                .withAny(ValuePropertyNames.BINARY_OVERHEDGE)
                .withAny(ValuePropertyNames.BINARY_SMOOTHING_FULLWIDTH).get();
        resultsWithExtraProperties.add(new ValueSpecification(name, targetSpec, properties));
    }/*from  w  ww.  java 2  s.com*/
    return results;
}

From source file:org.summer.dsl.model.types.util.Primitives.java

public JvmTypeReference asPrimitiveIfWrapperType(JvmTypeReference type) {
    return new AbstractTypeReferenceVisitor.InheritanceAware<JvmTypeReference>() {

        private Set<JvmType> visiting = Sets.newHashSetWithExpectedSize(2);

        @Override/*from   www .jav a 2s. c  o m*/
        public JvmTypeReference doVisitMultiTypeReference(JvmMultiTypeReference reference) {
            for (JvmTypeReference ref : reference.getReferences()) {
                JvmTypeReference refAsPrimitiveIfWrapper = visit(ref);
                if (refAsPrimitiveIfWrapper != ref)
                    return refAsPrimitiveIfWrapper;
            }
            return reference;
        }

        //cym comment
        //         @Override
        //         public JvmTypeReference doVisitParameterizedTypeReference(JvmParameterizedTypeReference type) {
        //            if(type.getType() instanceof JvmTypeParameter && visiting.add(type.getType())) {
        //               EList<JvmTypeConstraint> constraints = ((JvmTypeParameter)type.getType()).getConstraints();
        //               for(JvmUpperBound upperBound: filter(constraints, JvmUpperBound.class)) {
        //                  JvmTypeReference upperBoundType = upperBound.getTypeReference();
        //                  JvmTypeReference asPrimitive = visit(upperBoundType);
        //                  if(asPrimitive != upperBoundType) 
        //                     return asPrimitive;
        //               }
        //               return type;
        //            } else if (typeReferences.is(type, Byte.class)) {
        //               return typeReferences.getTypeForName(Byte.TYPE, type.getType());
        //            } else if (typeReferences.is(type, Short.class)) {
        //               return typeReferences.getTypeForName(Short.TYPE, type.getType());
        ////            } else if (typeReferences.is(type, Character.class)) {
        ////               return typeReferences.getTypeForName(Character.TYPE, type.getType());
        //            } else if (typeReferences.is(type, Integer.class)) {
        //               return typeReferences.getTypeForName(Integer.TYPE, type.getType());
        ////            } else if (typeReferences.is(type, Long.class)) {
        ////               return typeReferences.getTypeForName(Long.TYPE, type.getType());
        //            } else if (typeReferences.is(type, Float.class)) {
        //               return typeReferences.getTypeForName(Float.TYPE, type.getType());
        //            } else if (typeReferences.is(type, Double.class)) {
        //               return typeReferences.getTypeForName(Double.TYPE, type.getType());
        //            } else if (typeReferences.is(type, Boolean.class)) {
        //               return typeReferences.getTypeForName(Boolean.TYPE, type.getType());
        ////            } else if (typeReferences.is(type, Void.class)) {
        ////               return typeReferences.getTypeForName(Void.TYPE, type.getType());
        //            }
        //            return type;
        //         }

        @Override
        public JvmTypeReference doVisitParameterizedTypeReference(JvmParameterizedTypeReference typeRef) {
            Resource resource = typeRef.getType().eResource();
            if (typeRef.getType() instanceof JvmTypeParameter && visiting.add(typeRef.getType())) {
                EList<JvmTypeConstraint> constraints = ((JvmTypeParameter) typeRef.getType()).getConstraints();
                for (JvmUpperBound upperBound : filter(constraints, JvmUpperBound.class)) {
                    JvmTypeReference upperBoundType = upperBound.getTypeReference();
                    JvmTypeReference asPrimitive = visit(upperBoundType);
                    if (asPrimitive != upperBoundType)
                        return asPrimitive;
                }
                return typeRef;
            } else if (typeReferences.is(typeRef, Buildin.Byte.Type)) {
                return typeReferences.getTypeForName(Buildin.Byte.Type, typeRef.getType());
            } else if (typeReferences.is(typeRef, Buildin.Short.Type)) {
                return typeReferences.getTypeForName(Buildin.Short.Type, typeRef.getType());
                //            } else if (typeReferences.is(type, Character.class)) {
                //               return typeReferences.getTypeForName(Character.TYPE, type.getType());
            } else if (typeReferences.is(typeRef, Buildin.Integer.Type)) {
                return typeReferences.getTypeForName(Buildin.Integer.Type, typeRef.getType());
                //            } else if (typeReferences.is(type, Long.class)) {
                //               return typeReferences.getTypeForName(Long.TYPE, type.getType());
            } else if (typeReferences.is(typeRef, Buildin.Float.Type)) {
                return typeReferences.getTypeForName(Buildin.Float.Type, typeRef.getType());
            } else if (typeReferences.is(typeRef, Buildin.Double.Type)) {
                return typeReferences.getTypeForName(Buildin.Double.Type, typeRef.getType());
            } else if (typeReferences.is(typeRef, Buildin.Boolean.Type)) {
                return typeReferences.getTypeForName(Buildin.Boolean.Type, typeRef.getType());
                //            } else if (typeReferences.is(type, Void.class)) {
                //               return typeReferences.getTypeForName(Void.TYPE, type.getType());
            }
            return typeRef;
        }

        @Override
        public JvmTypeReference doVisitTypeReference(JvmTypeReference reference) {
            return reference;
        }

        @Override
        protected JvmTypeReference handleNullReference() {
            return null;
        }
    }.visit(type);

}

From source file:datafu.pig.sampling.SimpleRandomSampleWithReplacementVote.java

/**
 * Samples k integers from [0, n) without replacement efficiently.
 * //from ww  w .  j a  v a 2 s  . co  m
 * If k is small, we can repeatedly draw integers from [0, n) until there are k distinct
 * values. For each trial, with probability at least (n-k)/n, we can draw a new value.
 * So the expected number of trials is smaller than (k*n)/(n-k), which is a very rough
 * bound. If k is large, we use the selection-rejection sampling algorithm. Basically,
 * we want the running time to be O(k).
 * 
 */
private int[] sampleWithoutReplacement(int n, int k) {
    if (k == 0) {
        return new int[] {};
    }

    if (k < n / 3L) {
        Set<Integer> sample = Sets.newHashSetWithExpectedSize(k);

        // The expected number of iterations is less than 1.5*k
        while (sample.size() < k) {
            sample.add(_rdg.nextInt(0, n - 1));
        }

        return Ints.toArray(sample);
    } else {
        int[] sample = new int[k];

        int i = 0;
        for (int j = 0; j < n && i < k; ++j) {
            if (_rdg.nextUniform(0.0d, 1.0d) < 1.0d * (k - i) / (n - j)) {
                sample[i] = j;
                i++;
            }
        }

        return sample;
    }
}

From source file:com.opengamma.core.security.impl.CoalescingSecuritySource.java

@Override
public Map<UniqueId, Security> get(final Collection<UniqueId> uniqueIds) {
    if (!_fetching.compareAndSet(false, true)) {
        final MultipleCallback callback = new MultipleCallback(uniqueIds.size());
        for (UniqueId uniqueId : uniqueIds) {
            _pending.add(Pair.of(uniqueId, callback));
        }//from www  .j a  v  a 2  s.  com
        if (callback.waitForResult(_fetching)) {
            return callback.getSecurities();
        }
        // Request the pending queue
        final Collection<Pair<UniqueId, ? extends Callback>> pending = drainPending();
        final Set<UniqueId> request = Sets.newHashSetWithExpectedSize(pending.size());
        addPendingToRequest(pending, request);
        final Map<UniqueId, Security> fullResult;
        try {
            fullResult = getUnderlying().get(request);
            notifyPending(pending, fullResult);
        } catch (RuntimeException t) {
            errorPending(pending);
            throw t;
        } finally {
            _fetching.set(false);
            releaseOtherWritingThreads();
        }
        // We've either notified our own callback or another thread has already done it
        return callback.getSecurities();
    } else {
        Pair<UniqueId, ? extends Callback> e = _pending.poll();
        if (e == null) {
            // Direct request
            final Map<UniqueId, Security> result;
            try {
                result = getUnderlying().get(uniqueIds);
            } finally {
                _fetching.set(false);
                releaseOtherWritingThreads();
            }
            return result;
        } else {
            // Bulk request, e and the content of the pending queue
            final Collection<Pair<UniqueId, ? extends Callback>> pending = drainPending();
            pending.add(e);
            final Set<UniqueId> request = Sets.newHashSetWithExpectedSize(pending.size() + uniqueIds.size());
            request.addAll(uniqueIds);
            addPendingToRequest(pending, request);
            final Map<UniqueId, Security> fullResult;
            try {
                fullResult = getUnderlying().get(request);
                notifyPending(pending, fullResult);
            } catch (RuntimeException t) {
                errorPending(pending);
                throw t;
            } finally {
                _fetching.set(false);
                releaseOtherWritingThreads();
            }
            final Map<UniqueId, Security> result = Maps.newHashMapWithExpectedSize(uniqueIds.size());
            for (UniqueId uniqueId : uniqueIds) {
                final Security security = fullResult.get(uniqueId);
                if (security != null) {
                    result.put(uniqueId, security);
                }
            }
            return result;
        }
    }
}

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

/**
 * Find the bonds of a {@code molecule} which this model determined were
 * aromatic./*from   w w w  .  j  ava 2s .  co m*/
 *
 * <blockquote><pre>{@code
 * Aromaticity aromaticity = new Aromaticity(ElectronDonation.cdk(),
 *                                           Cycles.all());
 * IAtomContainer container = ...;
 * try {
 *     Set<IBond> bonds          = aromaticity.findBonds(container);
 *     int        nAromaticBonds = bonds.size();
 * } catch (CDKException e) {
 *     // cycle computation was intractable
 * }
 * }</pre></blockquote>
 *
 * @param molecule the molecule to apply the model to
 * @return the set of bonds which are aromatic
 * @throws CDKException a problem occurred with the cycle perception - one
 *                      can retry with a simpler cycle set
 */
public Set<IBond> findBonds(IAtomContainer molecule) throws CDKException {

    // build graph data-structures for fast cycle perception
    final EdgeToBondMap bondMap = EdgeToBondMap.withSpaceFor(molecule);
    final int[][] graph = GraphUtil.toAdjList(molecule, bondMap);

    // initial ring/cycle search and get the contribution from each atom
    final RingSearch ringSearch = new RingSearch(molecule, graph);
    final int[] electrons = model.contribution(molecule, ringSearch);

    final Set<IBond> bonds = Sets.newHashSetWithExpectedSize(molecule.getBondCount());

    // obtain the subset of electron contributions which are >= 0 (i.e.
    // allowed to be aromatic) - we then find the cycles in this subgraph
    // and 'lift' the indices back to the original graph using the subset
    // as a lookup
    final int[] subset = subset(electrons);
    final int[][] subgraph = GraphUtil.subgraph(graph, subset);

    // for each cycle if the electron sum is valid add the bonds of the
    // cycle to the set or aromatic bonds
    for (final int[] cycle : cycles.find(molecule, subgraph, subgraph.length).paths()) {
        if (checkElectronSum(cycle, electrons, subset)) {
            for (int i = 1; i < cycle.length; i++) {
                bonds.add(bondMap.get(subset[cycle[i]], subset[cycle[i - 1]]));
            }
        }
    }

    return bonds;
}