Example usage for com.google.common.collect Lists newArrayListWithExpectedSize

List of usage examples for com.google.common.collect Lists newArrayListWithExpectedSize

Introduction

In this page you can find the example usage for com.google.common.collect Lists newArrayListWithExpectedSize.

Prototype

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize) 

Source Link

Document

Creates an ArrayList instance to hold estimatedSize elements, plus an unspecified amount of padding; you almost certainly mean to call #newArrayListWithCapacity (see that method for further advice on usage).

Usage

From source file:com.cloudera.exhibit.core.PivotCalculator.java

@Override
public Iterable<Obs> apply(Exhibit exhibit) {
    Iterable<Obs> frame = fc.apply(exhibit);
    if (descriptor == null) {
        descriptor = initialize(exhibit == null ? null : exhibit.descriptor());
    }/* www . j  av a2 s  .co  m*/
    Map<List<Object>, List<Object>> valuesById = Maps.newHashMap();
    for (Obs obs : frame) {
        List<Object> idv = Lists.newArrayListWithExpectedSize(ids.size());
        for (String id : ids) {
            idv.add(obs.get(id));
        }
        List<Object> values = valuesById.get(idv);
        if (values == null) {
            values = Arrays.asList(new Object[descriptor.size() - ids.size()]);
            valuesById.put(idv, values);
        }
        List<String> keyValues = Lists.newArrayListWithExpectedSize(keys.size());
        for (String key : keys.keySet()) {
            Object v = obs.get(key);
            keyValues.add(v == null ? "null" : v.toString());
        }
        String lookupKey = Joiner.on('_').join(keyValues);
        for (ObsDescriptor.Field f : obs.descriptor()) {
            if (!ids.contains(f.name) && !keys.containsKey(f.name)) {
                String retField = new StringBuilder(f.name).append('_').append(lookupKey).toString();
                int index = descriptor.indexOf(retField);
                values.set(index - ids.size(), obs.get(f.name));
            }
        }
    }
    return Iterables.transform(valuesById.entrySet(),
            new Function<Map.Entry<List<Object>, List<Object>>, Obs>() {
                @Override
                public Obs apply(Map.Entry<List<Object>, List<Object>> e) {
                    List<Object> key = e.getKey();
                    key.addAll(e.getValue());
                    return new SimpleObs(descriptor, key);
                }
            });
}

From source file:eu.project.ttc.utils.TermSuiteUtils.java

public static String getGroupingKey(TermOccAnnotation annotation) {
    StringBuilder patternSb = new StringBuilder();
    List<String> lemmas = Lists.newArrayListWithExpectedSize(annotation.getWords().size());
    for (int i = 0; i < annotation.getWords().size(); i++) {
        patternSb.append(annotation.getPattern(i).toLowerCase());
        lemmas.add(annotation.getWords(i).getLemma());
    }//from   w w  w  .j a  v  a 2s . c om
    return toGroupingKey(patternSb, lemmas);
}

From source file:org.apache.pulsar.client.impl.PatternTopicsConsumerImpl.java

@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;/*from   ww  w.  jav a 2  s  .c  om*/
    }

    CompletableFuture<Void> recheckFuture = new CompletableFuture<>();
    List<CompletableFuture<Void>> futures = Lists.newArrayListWithExpectedSize(2);

    client.getLookup().getTopicsUnderNamespace(namespaceName).thenAccept(topics -> {
        if (log.isDebugEnabled()) {
            log.debug("Get topics under namespace {}, topics.size: {}", namespaceName.toString(),
                    topics.size());
            topics.forEach(topicName -> log.debug("Get topics under namespace {}, topic: {}",
                    namespaceName.toString(), topicName));
        }

        List<String> newTopics = PulsarClientImpl.topicsPatternFilter(topics, topicsPattern);
        List<String> oldTopics = PatternTopicsConsumerImpl.this.getTopics();

        futures.add(topicsChangeListener.onTopicsAdded(topicsListsMinus(newTopics, oldTopics)));
        futures.add(topicsChangeListener.onTopicsRemoved(topicsListsMinus(oldTopics, newTopics)));
        FutureUtil.waitForAll(futures).thenAccept(finalFuture -> recheckFuture.complete(null))
                .exceptionally(ex -> {
                    log.warn("[{}] Failed to recheck topics change: {}", topic, ex.getMessage());
                    recheckFuture.completeExceptionally(ex);
                    return null;
                });
    });

    // schedule the next re-check task
    client.timer().newTimeout(PatternTopicsConsumerImpl.this, Math.min(1, conf.getPatternAutoDiscoveryPeriod()),
            TimeUnit.MINUTES);
}

From source file:com.android.builder.core.JackProcessBuilder.java

@NonNull
public JackProcessBuilder addProguardFiles(@NonNull Collection<File> proguardFiles) {
    if (mProguardFiles == null) {
        mProguardFiles = Lists.newArrayListWithExpectedSize(proguardFiles.size());
    }/*from   w w w .j  a  v  a2s .  c  om*/

    mProguardFiles.addAll(proguardFiles);
    return this;
}

From source file:com.android.ide.eclipse.ddms.systrace.SystraceOptionsDialogV2.java

public SystraceOptionsDialogV2(Shell parentShell, List<SystraceTag> tags, List<String> apps) {
    super(parentShell);
    mCurrentApps = apps;/*from w  w w  .  j  a  v  a 2  s  .c o  m*/

    mCommonSupportedTags = Lists.newArrayListWithExpectedSize(tags.size());
    mAdvancedSupportedTags = Lists.newArrayListWithExpectedSize(tags.size());

    for (SystraceTag supportedTag : tags) {
        if (sCommonTags.contains(supportedTag.tag)) {
            mCommonSupportedTags.add(supportedTag);
        } else {
            mAdvancedSupportedTags.add(supportedTag);
        }
    }
}

From source file:edu.umich.robot.soar.OutputLink.java

/**
 * Update the output link looking for and instantiating new commands.
 *///  w  ww  .  ja  v a 2  s. com
void update() {
    // walk output link, creating and updating, marking keeps
    int children = ol.GetNumberChildren();

    if (logger.isTraceEnabled())
        logger.trace("OutputLink children: " + children);

    List<Long> seen = Lists.newArrayListWithExpectedSize(children);
    List<OLCommandPair> multicycles = Lists.newArrayListWithExpectedSize(children);

    for (int i = 0; i < children; ++i) {
        WMElement wme = ol.GetChild(i);
        Identifier id = wme.ConvertToIdentifier();
        if (id == null)
            continue;

        Long tt = Long.valueOf(wme.GetTimeTag());
        seen.add(tt);
        if (logger.isTraceEnabled())
            logger.trace("Seen tt: " + tt);

        OLCommandPair pair = commands.get(tt);
        if (pair != null) {
            // do new commands first so that they cancel older commands
            multicycles.add(pair);
            if (logger.isTraceEnabled())
                logger.trace("Added to multicycles: " + pair.command);
            continue;
        }

        try {
            pair = new OLCommandPair(cm.newInstance(id));
            if (pair.command == null)
                continue;

            commands.put(tt, pair);
            processCommand(pair);
        } catch (SoarCommandError e) {
            logger.error("Error with tt:" + e.getMessage());
        }
    }

    logger.trace("Processing multicycles");
    // do older commands next so that new commands cancel them
    for (OLCommandPair pair : multicycles) {
        if (logger.isTraceEnabled())
            logger.trace("Processing multicycle: " + pair.command);
        processCommand(pair);
    }

    // remove stale commands
    logger.trace("Processing stales");
    for (Iterator<Entry<Long, OLCommandPair>> iter = commands.entrySet().iterator(); iter.hasNext();) {
        Entry<Long, OLCommandPair> entry = iter.next();
        if (!seen.contains(entry.getKey())) {
            logger.trace("disposing " + entry.getKey());
            entry.getValue().command.dispose();
            iter.remove();
        }
    }
    logger.trace("OL Update done");
}

From source file:com.cloudera.oryx.kmeans.serving.generation.VectorFactory.java

public static VectorFactory create(MiningSchema schema, LocalTransformations transforms,
        List<ClusteringField> fields) {
    Map<FieldName, DerivedField> derived = Maps
            .newHashMapWithExpectedSize(transforms.getDerivedFields().size());
    for (DerivedField df : transforms.getDerivedFields()) {
        derived.put(df.getName(), df);/* w ww  .  j  a  v a  2 s  . c o  m*/
    }

    Multimap<FieldName, NumericUpdate> numeric = HashMultimap.create();
    Map<FieldName, Map<String, Update>> categorical = Maps.newHashMap();
    for (int j = 0; j < fields.size(); j++) {
        ClusteringField cf = fields.get(j);
        FieldName fn = cf.getField();
        if (derived.containsKey(fn)) {
            DerivedField df = derived.get(fn);
            Expression e = df.getExpression();
            if (e instanceof NormDiscrete) {
                NormDiscrete nd = (NormDiscrete) e;
                Map<String, Update> m = categorical.get(nd.getField());
                if (m == null) {
                    m = Maps.newHashMap();
                    categorical.put(nd.getField(), m);
                }
                m.put(nd.getValue(), new NumericUpdate(ONE, j, cf.getFieldWeight()));
            } else if (e instanceof Apply) {
                Apply apply = (Apply) e;
                if (!"ln".equals(apply.getFunction())) {
                    throw new UnsupportedOperationException(
                            "Unsupported function type: " + apply.getFunction());
                }
                FieldName f = ((FieldRef) apply.getExpressions().get(0)).getField();
                numeric.put(f, new NumericUpdate(LOG_VALUE, j, cf.getFieldWeight()));
            } else if (e instanceof NormContinuous) {
                NormContinuous nc = (NormContinuous) e;
                FieldName f = nc.getField();
                LinearNorm l1 = nc.getLinearNorms().get(0);
                LinearNorm l2 = nc.getLinearNorms().get(1);
                InterpolateFunction ifunc = new InterpolateFunction(l1.getOrig(), l1.getNorm(), l2.getOrig(),
                        l2.getNorm());
                numeric.put(f, new NumericUpdate(ifunc, j, cf.getFieldWeight()));
            } else {
                throw new UnsupportedOperationException("Unsupported expression type: " + e);
            }
        } else {
            numeric.put(fn, new NumericUpdate(VALUE, j, cf.getFieldWeight()));
        }
    }

    boolean sparse = 2 * schema.getMiningFields().size() <= fields.size();
    List<Set<Update>> updates = Lists.newArrayListWithExpectedSize(schema.getMiningFields().size());
    for (MiningField mf : schema.getMiningFields()) {
        FieldName fn = mf.getName();
        if (numeric.containsKey(fn)) {
            updates.add(ImmutableSet.<Update>copyOf(numeric.get(fn)));
        } else if (categorical.containsKey(fn)) {
            CategoricalUpdate u = new CategoricalUpdate(categorical.get(fn));
            updates.add(ImmutableSet.<Update>of(u));
        }
    }
    return new VectorFactory(sparse, fields.size(), updates);
}

From source file:org.apache.jclouds.profitbricks.rest.compute.function.ServerInDataCenterToNodeMetadata.java

@Inject
public ServerInDataCenterToNodeMetadata(
        Function<org.apache.jclouds.profitbricks.rest.domain.Volume, Volume> fnVolume,
        @Memoized Supplier<Set<? extends Location>> locations, ProfitBricksApi api,
        GroupNamingConvention.Factory groupNamingConvention) {
    this.fnVolume = fnVolume;
    this.locations = locations;
    this.api = api;
    this.groupNamingConvention = groupNamingConvention.createWithoutPrefix();
    this.fnCollectIps = new Function<List<Nic>, List<String>>() {
        @Override//from   w  ww .j  a  va 2s. c  o  m
        public List<String> apply(List<Nic> in) {
            List<String> ips = Lists.newArrayListWithExpectedSize(in.size());
            for (Nic nic : in) {
                ips.addAll(nic.properties().ips());
            }
            return ips;
        }
    };
}

From source file:com.cloudera.science.ml.client.cmd.LloydsCommand.java

@Override
public int execute(Configuration conf) throws IOException {
    Pipeline p = pipelineParams.create(KMeansAssignmentCommand.class, conf);
    PCollection<NamedVector> input = inputParams.getVectors(p);
    List<MLCenters> mlCenters = AvroIO.read(MLCenters.class, new File(centersFile));
    if (!centerIds.isEmpty()) {
        List<MLCenters> filter = Lists.newArrayListWithExpectedSize(centerIds.size());
        for (Integer centerId : centerIds) {
            filter.add(mlCenters.get(centerId));
        }//from   www .  j  a v  a 2  s .c  om
        mlCenters = filter;
    }

    KMeansParallel kmp = new KMeansParallel();
    List<Centers> initial = Lists.transform(mlCenters, VectorConvert.TO_CENTERS);
    List<Centers> output = kmp.lloydsAlgorithm(input, initial, numIterations, approx);
    if (computeCosts) {
        List<Double> costs = kmp.getCosts(input, output, approx).getValue();
        System.out.println("CenterId,Cost");
        for (int i = 0; i < costs.size(); i++) {
            int centerId = centerIds.isEmpty() ? i : centerIds.get(i);
            System.out.println(String.format("%d,%.4f", centerId, costs.get(i)));
        }
    }

    AvroIO.write(Lists.transform(output, VectorConvert.FROM_CENTERS), new File(outputCentersFile));
    p.done();
    return 0;
}

From source file:org.attribyte.api.pubsub.impl.server.NotificationMetricsServlet.java

@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

    String joinString = Strings.nullToEmpty(request.getParameter("joinWith")).trim();
    if (joinString.isEmpty())
        joinString = "_";
    boolean allowSlashInPrefix = true;
    if (request.getParameter("allowSlash") != null) {
        allowSlashInPrefix = request.getParameter("allowSlash").trim().equalsIgnoreCase("true");
    }/*from  w w w .  ja v  a 2 s  .c o m*/

    List<String> path = splitPath(request);
    String obj = path.size() > 0 ? path.get(0) : null;
    String[] topics = request.getParameterValues("name");

    if (obj == null) {
        MetricRegistry registry = new MetricRegistry();
        registry.register("", endpoint.getGlobalNotificationMetrics());

        String json = mapper.writer().writeValueAsString(registry);
        response.setContentType("application/json");
        response.getWriter().print(json);
        response.getWriter().flush();
    } else if (obj.equals("topic")) {
        final List<NotificationMetrics> metrics;
        if (topics != null && topics.length > 0) {
            metrics = Lists.newArrayListWithExpectedSize(topics.length);
            for (String topicName : topics) {
                Topic topic = resolveTopic(topicName);
                if (topic != null) {
                    NotificationMetrics topicMetrics = endpoint.getNotificationMetrics(topic.getId());
                    if (topicMetrics != null)
                        metrics.add(topicMetrics);
                }
            }
        } else {
            String sortStr = request.getParameter("sort");
            if (sortStr == null)
                sortStr = "";
            NotificationMetrics.Sort sort = sortMap.get(sortStr);
            if (sort == null)
                sort = NotificationMetrics.Sort.THROUGHPUT_DESC;
            String limitStr = request.getParameter("limit");
            int limit = 25;
            if (limitStr != null) {
                try {
                    limit = Integer.parseInt(limitStr);
                } catch (NumberFormatException nfe) {
                    limit = 25;
                }
            }
            metrics = endpoint.getNotificationMetrics(sort, limit);
        }

        MetricRegistry registry = new MetricRegistry();
        for (NotificationMetrics callbackMetrics : metrics) {
            String prefix = getTopicPrefix(callbackMetrics.topicId, joinString, allowSlashInPrefix);
            if (prefix != null) {
                registry.register(prefix, callbackMetrics);
            }
        }

        String json = mapper.writer().writeValueAsString(registry);
        response.setContentType("application/json");
        response.getWriter().print(json);
        response.getWriter().flush();
    } else {
        response.sendError(404);
    }
}