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

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

Introduction

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

Prototype

@GwtCompatible(serializable = true)
public static <E> ArrayList<E> newArrayListWithCapacity(int initialArraySize) 

Source Link

Document

Creates an ArrayList instance backed by an array with the specified initial size; simply delegates to ArrayList#ArrayList(int) .

Usage

From source file:edu.byu.nlp.classify.MalletMaxentTrainer.java

/**
 * The trainer takes care of converting the dataset into types that 
 * mallet can work with. Labels are not converted here, but 
 * are passed in separately during training.
 *///from w ww  . jav  a  2s . c  o  m
public static MalletMaxentTrainer build(Dataset data) {

    final MalletMaxentTrainer trainer = new MalletMaxentTrainer();

    trainer.externalInstances = Lists.newArrayListWithCapacity(data.getInfo().getNumDocuments());
    trainer.instances = new cc.mallet.types.Instance[data.getInfo().getNumDocuments()];
    trainer.dataAlphabet = new Alphabet();
    trainer.dataAlphabet.startGrowth();
    trainer.targetAlphabet = new LabelAlphabet();
    trainer.targetAlphabet.startGrowth();

    // create identity mallet alphabets (so that our indices correspond exactly to theirs)
    for (int f = 0; f < data.getInfo().getNumFeatures(); f++) {
        trainer.dataAlphabet.lookupIndex(f, true);
    }
    trainer.dataAlphabet.stopGrowth();
    for (int l = 0; l < data.getInfo().getNumClasses(); l++) {
        trainer.targetAlphabet.lookupLabel(l, true);
    }
    trainer.targetAlphabet.stopGrowth();

    // alphabet sanity check #1 (make sure mallet alphabets return identity mappings
    Preconditions.checkState(data.getInfo().getNumFeatures() == trainer.dataAlphabet.size());
    Preconditions.checkState(data.getInfo().getNumClasses() == trainer.targetAlphabet.size());
    for (int f = 0; f < trainer.dataAlphabet.size(); f++) {
        Preconditions.checkState(trainer.dataAlphabet.lookupIndex(f) == f);
        Preconditions.checkState(trainer.dataAlphabet.lookupObject(f).equals(new Integer(f)));
    }
    for (int f = 0; f < trainer.targetAlphabet.size(); f++) {
        Preconditions.checkState(trainer.targetAlphabet.lookupIndex(f) == f);
        Preconditions.checkState(trainer.targetAlphabet.lookupLabel(f).getIndex() == f);
        Preconditions.checkState(trainer.targetAlphabet.lookupObject(f).equals(new Integer(f)));
    }

    // alphabet sanity check #2 (make sure every instance in the data has valid mallet data and label alphabet entries) 
    // this would only fail if our indexers were not working properly (there was a gap somewhere among 
    // the existing indices)
    for (DatasetInstance inst : data) {
        // visit the data (to make sure all features and labels were added correctly)
        inst.asFeatureVector().visitSparseEntries(new EntryVisitor() {
            @Override
            public void visitEntry(int index, double value) {
                Preconditions.checkState(trainer.dataAlphabet.lookupIndex(index, false) >= 0);
            }
        });
        if (inst.hasLabel()) { // ignore null label but use hidden labels to help ensure good alphabet coverage (no cheating here)
            Preconditions.checkState(trainer.targetAlphabet.lookupIndex(inst.getLabel()) >= 0);
        }
    }

    // convert each dataset instance to a mallet instance 
    for (Enumeration<DatasetInstance> item : Iterables2.enumerate(data)) {
        // convert feature vector
        trainer.instances[item.getIndex()] = convert(trainer.dataAlphabet, item.getElement());
        // remember the original instance
        trainer.externalInstances.add(item.getElement());
    }

    return trainer;
}

From source file:com.googlesource.gerrit.plugins.cookbook.HelloTopMenu.java

@Inject
public HelloTopMenu(@PluginName String pluginName) {
    String baseUrl = "/plugins/" + pluginName + "/";
    List<MenuItem> menuItems = Lists.newArrayListWithCapacity(2);
    menuItems.add(new MenuItem("Greeting", "#/x/" + pluginName + "/", ""));
    menuItems.add(new MenuItem("Documentation", baseUrl));
    menuEntries = Lists.newArrayListWithCapacity(2);
    menuEntries.add(new MenuEntry("Cookbook", menuItems));
    menuEntries.add(new MenuEntry("Projects",
            Lists.newArrayList(new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/"))));
}

From source file:com.googlesource.gerrit.plugins.examples.topmenu.HelloTopMenu.java

@Inject
public HelloTopMenu(@PluginName String pluginName) {
    String baseUrl = "/plugins/" + pluginName + "/";
    List<MenuItem> menuItems = Lists.newArrayListWithCapacity(2);
    menuItems.add(new MenuItem("Greeting", "#/x/" + pluginName + "/", ""));
    menuItems.add(new MenuItem("Documentation", baseUrl));
    menuEntries = Lists.newArrayListWithCapacity(2);
    menuEntries.add(new MenuEntry("Examples", menuItems));
    menuEntries.add(new MenuEntry("Projects",
            Lists.newArrayList(new MenuItem("Browse Repositories", "https://gerrit.googlesource.com/"))));
}

From source file:com.ojuslabs.oct.xlate.mdl.SdfIterator.java

/**
 * @param istream/* w  w  w. ja  v  a  2s . c  o  m*/
 *            An input stream from the underlying SdfFile.
 */
SdfIterator(Reader reader) {
    _reader = new BufferedReader(reader, Constants.IO_BUFFER_SIZE);
    _text = Lists.newArrayListWithCapacity(Constants.LIST_SIZE_L);
}

From source file:org.glowroot.agent.model.DetailMapWriter.java

private static List<Trace.DetailEntry> mapToProto(Map<?, ?> map) {
    List<Trace.DetailEntry> entries = Lists.newArrayListWithCapacity(map.size());
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        Object key = entry.getKey();
        if (key == null) {
            // skip invalid data
            logger.warn("detail map has null key");
            continue;
        }//from w w  w.j a va2  s.  c  om
        String name;
        if (key instanceof String) {
            name = (String) key;
        } else {
            name = convertToStringAndTruncate(key);
        }
        entries.add(createDetailEntry(name, entry.getValue()));
    }
    return entries;
}

From source file:org.geogit.rest.repository.RepositoryResource.java

@Override
protected List<DataFormat> createSupportedFormats(Request request, Response response) {
    List<DataFormat> formats = Lists.newArrayListWithCapacity(3);

    formats.add(new FreemarkerFormat(RepositoryResource.class.getSimpleName() + ".ftl", getClass(),
            MediaType.TEXT_HTML));

    return formats;
}

From source file:com.twitter.graphjet.algorithms.counting.user.TopSecondDegreeByCountUserRecsGenerator.java

private static List<RecommendationInfo> getRecommendationsFromNodes(
        TopSecondDegreeByCountRequestForUser request, PriorityQueue<NodeInfo> topNodes) {
    List<RecommendationInfo> outputResults = Lists.newArrayListWithCapacity(topNodes.size());
    int maxNumSocialProofs = request.getMaxNumSocialProofs();

    while (!topNodes.isEmpty()) {
        NodeInfo nodeInfo = topNodes.poll();

        Map<Byte, LongList> topSocialProofs = GeneratorHelper.pickTopSocialProofs(nodeInfo.getSocialProofs(),
                maxNumSocialProofs);//from  w w w  .  j a  v  a  2s  .c  o m

        UserRecommendationInfo userRecs = new UserRecommendationInfo(nodeInfo.getValue(), nodeInfo.getWeight(),
                topSocialProofs);
        outputResults.add(userRecs);
    }
    Collections.reverse(outputResults);
    return outputResults;
}

From source file:com.opengamma.web.server.push.analytics.formatting.LabelledMatrix1DFormatter.java

@Override
public List<List<String>> formatForExpandedDisplay(LabelledMatrix1D value, ValueSpecification valueSpec) {
    int length = value.getKeys().length;
    List<List<String>> results = Lists.newArrayListWithCapacity(length);
    for (int i = 0; i < length; i++) {
        Object labelObject = value.getLabels()[i];
        String label = labelObject instanceof ExternalId ? ((ExternalId) labelObject).getValue()
                : labelObject.toString();
        String formattedValue = _doubleFormatter.formatForDisplay(value.getValues()[i], valueSpec);
        List<String> rowResults = ImmutableList.of(label, formattedValue);
        results.add(rowResults);//from w ww  .  j a  v a 2 s  .  co m
    }
    return results;
}

From source file:org.plista.kornakapi.core.recommender.ParallelTopItems.java

public static List<RecommendedItem> getTopItems(int howMany, int numThreads, FastIDSet possibleItemIDs,
        final IDRescorer rescorer, final TopItems.Estimator<Long> estimator) throws TasteException {

    Preconditions.checkArgument(numThreads > 1);
    Preconditions.checkNotNull(possibleItemIDs);
    Preconditions.checkNotNull(estimator);

    //long s = System.currentTimeMillis();

    long[] itemIDsToEstimate = possibleItemIDs.toArray();

    //long d = System.currentTimeMillis() - s;
    //System.out.println("Preparation " + d);

    //s = System.currentTimeMillis();
    ExecutorService queue = Executors.newFixedThreadPool(numThreads);

    int fromIndex = 0;
    List<EstimationWorker> estimatorWorkers = Lists.newArrayListWithCapacity(numThreads);
    for (int n = 0; n < numThreads; n++) {

        int toIndex = Math.min(fromIndex + itemIDsToEstimate.length / numThreads, itemIDsToEstimate.length);
        EstimationWorker worker = new EstimationWorker(howMany, itemIDsToEstimate, fromIndex, toIndex, rescorer,
                estimator);/*from ww w  . j  a  v  a2s  .  c  o  m*/
        estimatorWorkers.add(worker);
        queue.execute(worker);
        fromIndex = toIndex;
    }

    queue.shutdown();
    try {
        queue.awaitTermination(5, TimeUnit.SECONDS);
    } catch (InterruptedException e) {
        throw new RuntimeException(e);
    }
    //d = System.currentTimeMillis() - s;
    //System.out.println("Estimation " + d);

    List<RecommendedItem> topItems = Lists.newArrayList();
    for (int n = 0; n < numThreads; n++) {
        topItems.addAll(estimatorWorkers.get(n).topItems);
    }

    if (topItems.isEmpty()) {
        return Collections.EMPTY_LIST;
    }
    if (topItems.size() < howMany) {
        howMany = topItems.size();
    }
    Collections.sort(topItems, ByValueRecommendedItemComparator.getInstance());
    List<RecommendedItem> recommendedItems = topItems.subList(0, howMany);

    return recommendedItems;
}

From source file:at.molindo.notify.dao.memory.MemoryTemplateDAO.java

@Override
public List<Template> findTemplates(String key) {
    synchronized (_templates) {
        List<Template> templates = _templates.get(key);
        if (templates == null) {
            return Lists.newArrayListWithCapacity(0);
        } else {/* w  w w. ja  v a 2  s  .c om*/
            templates = Lists.newArrayList(templates);
            ListIterator<Template> iter = templates.listIterator();
            while (iter.hasNext()) {
                iter.set(iter.next().clone());
            }
            return templates;
        }
    }
}