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:com.spotify.apollo.meta.model.CallsInfo.java

Model.EndpointsInfo getEndpointsInfo() {
    endpointsInfo.endpoints = Lists.newArrayListWithCapacity(endpoints.size());
    for (EndpointInfoGatherer endpoint : endpoints.values()) {
        endpointsInfo.endpoints.add(endpoint.endpointInfo());
    }//ww  w.j  a  v  a  2  s. c o m
    return endpointsInfo;
}

From source file:org.summer.dsl.xbase.typesystem.util.Multimaps2.java

/**
 * Constructs an empty {@code ListMultimap} with enough capacity to hold the specified numbers of keys and values
 * without resizing. It uses a linked map internally.
 * /*w ww .  ja v  a2 s  . c o m*/
 * @param expectedKeys
 *            the expected number of distinct keys
 * @param expectedValuesPerKey
 *            the expected average number of values per key
 * @throws IllegalArgumentException
 *             if {@code expectedKeys} or {@code expectedValuesPerKey} is negative
 */
public static <K, V> ListMultimap<K, V> newLinkedHashListMultimap(int expectedKeys,
        final int expectedValuesPerKey) {
    return Multimaps.newListMultimap(new LinkedHashMap<K, Collection<V>>(expectedKeys),
            new Supplier<List<V>>() {
                public List<V> get() {
                    return Lists.newArrayListWithCapacity(expectedValuesPerKey);
                }
            });
}

From source file:org.apache.mahout.math.hadoop.similarity.cooccurrence.TopElementsQueue.java

public List<MutableElement> getTopElements() {
    List<MutableElement> topElements = Lists.newArrayListWithCapacity(maxSize);
    while (size() > 0) {
        MutableElement top = pop();/*www. j av a 2  s .c om*/
        // filter out "sentinel" objects necessary for maintaining an efficient priority queue
        if (top.index() != SENTINEL_INDEX) {
            topElements.add(top);
        }
    }
    Collections.reverse(topElements);
    return topElements;
}

From source file:net.minecraftforge.gradle.util.caching.CacheUtil.java

@SuppressWarnings("rawtypes")
protected static String getHashes(Annotated output, List<Annotated> inputs, ICachableTask task)
        throws NoSuchMethodException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException,
        InvocationTargetException {
    // TODO: CONVERT TO CacheFile
    List<String> hashes = Lists.newArrayListWithCapacity(inputs.size() + 5);

    hashes.addAll(Constants.hashAll(task.getProject().file(output.getValue(task))));

    for (Annotated input : inputs) {
        AnnotatedElement m = input.getElement();
        Object val = input.getValue(task);

        if (val == null && m.isAnnotationPresent(Optional.class)) {
            hashes.add("null");
        } else if (m.isAnnotationPresent(InputFile.class)) {
            hashes.add(Constants.hash(task.getProject().file(input.getValue(task))));
            LOGGER.debug(//ww w  . ja  va2  s .  c o  m
                    Constants.hash(task.getProject().file(input.getValue(task))) + " " + input.getValue(task));
        } else if (m.isAnnotationPresent(InputDirectory.class)) {
            File dir = (File) input.getValue(task);
            hashes.addAll(Constants.hashAll(dir));
        } else if (m.isAnnotationPresent(InputFiles.class)) {
            FileCollection files = (FileCollection) input.getValue(task);
            for (File file : files.getFiles()) {
                String hash = Constants.hash(file);
                hashes.add(hash);
                LOGGER.debug(hash + " " + input.getValue(task));
            }
        } else
        // just @Input
        {
            Object obj = input.getValue(task);

            while (obj instanceof Closure)
                obj = ((Closure) obj).call();

            if (obj instanceof String) {
                hashes.add(Constants.hash((String) obj));
                LOGGER.debug(Constants.hash((String) obj) + " " + (String) obj);
            } else if (obj instanceof File) {
                File file = (File) obj;
                if (file.isDirectory()) {
                    List<File> files = Arrays.asList(file.listFiles());
                    Collections.sort(files);
                    for (File i : files) {
                        hashes.add(Constants.hash(i));
                        LOGGER.debug(Constants.hash(i) + " " + i);
                    }
                } else {
                    hashes.add(Constants.hash(file));
                    LOGGER.debug(Constants.hash(file) + " " + file);
                }
            } else if (obj instanceof PatternSet) {
                PatternSet set = (PatternSet) obj;
                hashes.add(Constants.hash("" + set.isCaseSensitive() + " " + set.getIncludes().toString() + " "
                        + set.getExcludes().toString() + " " + set.getIncludeSpecs().size() + " "
                        + set.getExcludeSpecs().size()));
            } else {
                hashes.add(Constants.hash(obj.toString()));
            }
        }
    }

    return Joiner.on(Constants.NEWLINE).join(hashes);
}

From source file:org.apache.mahout.common.iterator.FixedSizeSamplingIterator.java

public FixedSizeSamplingIterator(int size, Iterator<T> source) {
    List<T> buf = Lists.newArrayListWithCapacity(size);
    int sofar = 0;
    Random random = RandomUtils.getRandom();
    while (source.hasNext()) {
        T v = source.next();/*from w w w.ja v a 2s  .  c o m*/
        sofar++;
        if (buf.size() < size) {
            buf.add(v);
        } else {
            int position = random.nextInt(sofar);
            if (position < buf.size()) {
                buf.set(position, v);
            }
        }
    }
    delegate = buf.iterator();
}

From source file:uk.co.danielrendall.metaphor.parsers.COLOR_DEFParser.java

@Override
protected COLOR_DEF doParse(PushbackInputStream in) throws ParseException {
    Record.Options options = readOptions(in);
    // default is RGB (3 colours) unless CMYK
    int listSize = options.color_cmyk() ? 4 : 3;
    List<Integer> colorValues = Lists.newArrayListWithCapacity(listSize);
    for (int i = 0; i < listSize; i++) {
        colorValues.add(i, readSimple16BitInteger(in));
    }/*from ww  w  .j  a  va 2s  . c om*/
    String name = options.color_name() ? readNullTerminatedString(in) : "";
    return new COLOR_DEF(options, colorValues, name);
}

From source file:com.cloudera.impala.analysis.CollectionStructType.java

public static CollectionStructType createArrayStructType(ArrayType arrayType) {
    Type itemType = arrayType.getItemType();
    ArrayList<StructField> fields = Lists.newArrayListWithCapacity(2);
    // The item field name comes before the pos field name so that a path to the
    // stored item corresponds to its physical path.
    fields.add(new StructField(Path.ARRAY_ITEM_FIELD_NAME, itemType));
    fields.add(new StructField(Path.ARRAY_POS_FIELD_NAME, ScalarType.BIGINT));
    return new CollectionStructType(fields, false);
}

From source file:com.twitter.nodes.utils.Futures.java

/**
 * Wait for a map of futures and return a future of map, with the keys mapping to the value
 * returned from corresponding futures./*from   w  w w. ja v  a2 s .c  o m*/
 */
public static <K, V> Future<Map<K, V>> collect(final Map<K, Future<V>> futures) {
    try {
        List<Future<Tuple2<K, V>>> entries = Lists.newArrayListWithCapacity(futures.size());
        for (final Map.Entry<K, Future<V>> entry : futures.entrySet()) {
            entries.add(map(entry.getValue(), new Function0<Tuple2<K, V>>() {
                public Tuple2<K, V> apply() {
                    try {
                        return scala.Tuple2$.MODULE$.apply(entry.getKey(), Await.result(entry.getValue()));
                    } catch (Exception e) {
                        return Throwables.unchecked(e);
                    }
                }
            }));
        }

        final Future<List<Tuple2<K, V>>> listFuture = Future.collect(entries);

        return map(listFuture, new Function0<Map<K, V>>() {
            public Map<K, V> apply() {
                Map<K, V> result = Maps.newHashMapWithExpectedSize(futures.size());
                try {
                    for (Tuple2<K, V> pair : Await.result(listFuture)) {
                        result.put(pair._1(), pair._2());
                    }
                    return result;
                } catch (Exception e) {
                    return Throwables.unchecked(e);
                }
            }
        });
    } catch (Exception e) {
        return Throwables.unchecked(e);
    }
}

From source file:org.apache.kylin.cube.cuboid.algorithm.generic.CuboidEncoder.java

public List<Long> toCuboidList(BitSet bits) {
    List<Long> cuboids = Lists.newArrayListWithCapacity(bits.cardinality());
    for (int i = bits.nextSetBit(0); i >= 0; i = bits.nextSetBit(i + 1)) {
        cuboids.add(selectionCuboids.get(i));
    }//  ww w  . ja va 2s . com
    return cuboids;
}

From source file:org.apache.kylin.cube.CubeValidator.java

/**
 * Validates://from  w  w  w.j a  v  a  2s  . c om
 * - consistent isOffsetsOn()
 * - for all ready segments, sourceOffset MUST have no overlaps, SHOULD have no holes
 * - for all new segments, sourceOffset MUST have no overlaps, MUST contain a ready segment if overlaps with it
 * - for all new segments, sourceOffset SHOULD fit/connect another segments
 * - dateRange does not matter any more
 */
public static void validate(Collection<CubeSegment> segments) {
    if (segments == null || segments.isEmpty())
        return;

    // make a copy, don't modify given list
    List<CubeSegment> all = Lists.newArrayList(segments);
    Collections.sort(all);

    // check consistent isOffsetsOn()
    boolean isOffsetsOn = all.get(0).isSourceOffsetsOn();
    for (CubeSegment seg : all) {
        seg.validate();
        if (seg.isSourceOffsetsOn() != isOffsetsOn)
            throw new IllegalStateException("Inconsistent isOffsetsOn for segment " + seg);
    }

    List<CubeSegment> ready = Lists.newArrayListWithCapacity(all.size());
    List<CubeSegment> news = Lists.newArrayListWithCapacity(all.size());
    for (CubeSegment seg : all) {
        if (seg.getStatus() == SegmentStatusEnum.READY)
            ready.add(seg);
        else
            news.add(seg);
    }

    // for all ready segments, sourceOffset MUST have no overlaps, SHOULD have no holes
    CubeSegment pre = null;
    for (CubeSegment seg : ready) {
        if (pre != null) {
            if (pre.sourceOffsetOverlaps(seg))
                throw new IllegalStateException("Segments overlap: " + pre + " and " + seg);
            if (pre.getSourceOffsetEnd() < seg.getSourceOffsetStart())
                logger.warn("Hole between adjacent READY segments " + pre + " and " + seg);
        }
        pre = seg;
    }

    // for all other segments, sourceOffset MUST have no overlaps, MUST contain a ready segment if overlaps with it
    pre = null;
    for (CubeSegment seg : news) {
        if (pre != null) {
            if (pre.sourceOffsetOverlaps(seg))
                throw new IllegalStateException("Segments overlap: " + pre + " and " + seg);
        }
        pre = seg;

        for (CubeSegment aReady : ready) {
            if (seg.sourceOffsetOverlaps(aReady) && !seg.sourceOffsetContains(aReady))
                throw new IllegalStateException("Segments overlap: " + aReady + " and " + seg);
        }
    }

    // for all other segments, sourceOffset SHOULD fit/connect other segments
    for (CubeSegment seg : news) {
        Pair<Boolean, Boolean> pair = fitInSegments(all, seg);
        boolean startFit = pair.getFirst();
        boolean endFit = pair.getSecond();

        if (!startFit)
            logger.warn("NEW segment start does not fit/connect with other segments: " + seg);
        if (!endFit)
            logger.warn("NEW segment end does not fit/connect with other segments: " + seg);
    }
}