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.mgmtp.jfunk.common.random.RandomCollection.java

/**
 * Resets this object so it behaves like a newly constructed instance.
 *//*from  w ww.ja v  a  2 s .c om*/
@Override
public void reset() {
    this.priorityElements = Lists.newArrayList(originalElements);
    Collections.shuffle(priorityElements);
    this.currentElements = Lists.newArrayListWithExpectedSize(2 * originalElements.size());
    this.currentElements.addAll(originalElements);
}

From source file:org.apache.phoenix.mapreduce.PhoenixRecordReader.java

@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    final PhoenixInputSplit pSplit = (PhoenixInputSplit) split;
    final List<Scan> scans = pSplit.getScans();
    try {//from   w w  w .  j a  v a  2 s .co  m
        List<PeekingResultIterator> iterators = Lists.newArrayListWithExpectedSize(scans.size());
        StatementContext ctx = queryPlan.getContext();
        ReadMetricQueue readMetrics = ctx.getReadMetricsQueue();
        String tableName = queryPlan.getTableRef().getTable().getPhysicalName().getString();
        for (Scan scan : scans) {
            final TableResultIterator tableResultIterator = new TableResultIterator(queryPlan.getContext(),
                    queryPlan.getTableRef(), scan, readMetrics.allotMetric(SCAN_BYTES, tableName));
            PeekingResultIterator peekingResultIterator = LookAheadResultIterator.wrap(tableResultIterator);
            iterators.add(peekingResultIterator);
        }
        ResultIterator iterator = queryPlan.useRoundRobinIterator()
                ? RoundRobinResultIterator.newIterator(iterators, queryPlan)
                : ConcatResultIterator.newIterator(iterators);
        if (queryPlan.getContext().getSequenceManager().getSequenceCount() > 0) {
            iterator = new SequenceResultIterator(iterator, queryPlan.getContext().getSequenceManager());
        }
        this.resultIterator = iterator;
        // Clone the row projector as it's not thread safe and would be used simultaneously by
        // multiple threads otherwise.
        this.resultSet = new PhoenixResultSet(this.resultIterator, queryPlan.getProjector().cloneIfNecessary(),
                queryPlan.getContext());
    } catch (SQLException e) {
        LOG.error(String.format(" Error [%s] initializing PhoenixRecordReader. ", e.getMessage()));
        Throwables.propagate(e);
    }
}

From source file:com.cloudera.nav.sdk.client.NavigatorPlugin.java

/**
 * Currently this is unsupported. Instead, a generic custom entity is
 * being used by Navigator./*from   w w  w  .jav  a  2s . co m*/
 *
 * Search for classes defined using the @MClass annotation
 * in the given package. Registers all found classes with Navigator
 * @param packageName
 */
@SuppressWarnings("unchecked")
public MetadataModel registerModels(String packageName) {
    Reflections ref = new Reflections(packageName + ".");
    Set<Class<?>> types = ref.getTypesAnnotatedWith(MClass.class);
    Collection<Class<Entity>> modelClasses = Lists.newArrayListWithExpectedSize(types.size() + 1);
    for (Class<?> aClass : types) {
        Preconditions.checkArgument(Entity.class.isAssignableFrom(aClass));
        modelClasses.add((Class<Entity>) aClass);
    }
    if (modelClasses.size() > 0) {
        LOG.info("Registering models: {}", modelClasses);
        return registerModels(modelClasses);
    } else {
        LOG.info("No models to be registered in package {}", packageName);
        return null;
    }
}

From source file:org.eclipse.xtext.resource.containers.StateBasedContainerManager.java

protected List<IContainer> getVisibleContainers(List<String> handles,
        IResourceDescriptions resourceDescriptions) {
    if (handles.isEmpty())
        return Collections.emptyList();
    List<IContainer> result = Lists.newArrayListWithExpectedSize(handles.size());
    for (String handle : handles) {
        IContainer container = createContainer(handle, resourceDescriptions);
        if (!container.isEmpty() || result.isEmpty())
            result.add(container);/*from w w  w .  j  a v a2  s.  co  m*/
    }
    return result;
}

From source file:com.cloudera.science.ml.hcatalog.HCatalog.java

public static HCatSchema getHCatSchema(Spec spec) {
    if (spec instanceof HCatalogSpec) {
        return ((HCatalogSpec) spec).getImpl();
    }/*  w  w w  .j a  v a 2  s .c  o m*/
    List<HCatFieldSchema> fields = Lists.newArrayListWithExpectedSize(spec.size());
    try {
        for (int i = 0; i < spec.size(); i++) {
            FieldSpec fs = spec.getField(i);
            DataType dt = fs.spec().getDataType();
            switch (dt) {
            case BOOLEAN:
                fields.add(new HCatFieldSchema(fs.name(), Type.BOOLEAN, ""));
                break;
            case INT:
                fields.add(new HCatFieldSchema(fs.name(), Type.INT, ""));
                break;
            case DOUBLE:
                fields.add(new HCatFieldSchema(fs.name(), Type.DOUBLE, ""));
                break;
            case STRING:
                fields.add(new HCatFieldSchema(fs.name(), Type.STRING, ""));
                break;
            case LONG:
                fields.add(new HCatFieldSchema(fs.name(), Type.BIGINT, ""));
                break;
            default:
                throw new UnsupportedOperationException("Unhandled data type = " + dt);
            }
        }
    } catch (HCatException e) {
        throw new RuntimeException(e);
    }
    return new HCatSchema(fields);
}

From source file:client.DockerPackageClient.java

private F.Promise<List<WSResponse>> concurrentExecute(final List<WSRequest> reqs, final int concurrency) {
    if (concurrency <= 0) {
        throw new IllegalArgumentException("concurrency must be >= 1");
    }//from   w ww . j ava 2 s  . c o m

    // Maintains the 'lines' of concurrent requests
    final ArrayList<F.Promise<WSResponse>> concurrentReqs = Lists.newArrayListWithExpectedSize(concurrency);
    for (int i = 0; i < concurrency; i++) {
        // Dummy promises
        concurrentReqs.add(F.Promise.pure(null));
    }

    int concurrentCount = 0;
    final ArrayList<F.Promise<WSResponse>> results = new ArrayList<>(reqs.size());

    for (final WSRequest next : reqs) {
        final int concurrentIndex = concurrentCount % concurrency;
        final F.Promise<WSResponse> prev = concurrentReqs.get(concurrentIndex);
        final F.Promise<WSResponse> responsePromise = prev.flatMap(dontCare -> next.execute());
        results.add(responsePromise);
        concurrentReqs.add(concurrentIndex, responsePromise);

        concurrentCount += 1;
    }

    return F.Promise.sequence(results);
}

From source file:com.yahoo.yqlplus.engine.rules.NormalizeJoinExpression.java

private OperatorNode<ExpressionOperator> normalizeJoinClause(Set<String> leftSources, Set<String> rightSources,
        OperatorNode<ExpressionOperator> joinExpr) {
    switch (joinExpr.getOperator()) {
    case AND: {//from   www. j a  v  a 2  s  . co  m
        List<OperatorNode<ExpressionOperator>> clauses = joinExpr.getArgument(0);
        List<OperatorNode<ExpressionOperator>> newClauses = Lists.newArrayListWithExpectedSize(clauses.size());
        boolean hasNew = false;
        for (OperatorNode<ExpressionOperator> clause : clauses) {
            OperatorNode<ExpressionOperator> newClause = normalizeJoinClause(leftSources, rightSources, clause);
            if (newClause != clause) {
                hasNew = true;
            }
            newClauses.add(newClause);
        }
        if (hasNew) {
            return OperatorNode.create(joinExpr.getLocation(), joinExpr.getAnnotations(),
                    joinExpr.getOperator(), newClauses);
        }
        return joinExpr;
    }
    case EQ: {
        OperatorNode<ExpressionOperator> leftExpr = joinExpr.getArgument(0);
        OperatorNode<ExpressionOperator> rightExpr = joinExpr.getArgument(1);
        Set<String> leftReferenced = findReferencedSources(leftExpr);
        Set<String> rightReferenced = findReferencedSources(rightExpr);
        boolean ll = !Sets.intersection(leftSources, leftReferenced).isEmpty();
        boolean lr = !Sets.intersection(leftSources, rightReferenced).isEmpty();
        boolean rl = !Sets.intersection(rightSources, leftReferenced).isEmpty();
        boolean rr = !Sets.intersection(rightSources, rightReferenced).isEmpty();
        // ll - left expr references left sources
        // lr - left expr references right sources
        // rl - right expr references left sources
        // rr - right expr references right sources
        // verify neither expr references BOTH sides
        if (ll && lr) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality LEFT side references BOTH sides of JOIN");
        } else if (rl && rr) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality RIGHT side references BOTH sides of JOIN");
        } else if (!(ll || lr)) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality LEFT side references NEITHER side of JOIN");
        } else if (!(rl || rr)) {
            throw new ProgramCompileException(joinExpr.getLocation(),
                    "JOIN expression equality RIGHT side references NEITHER side of JOIN");
        }
        // normalize ordering so left side of EQ refers to left side of join
        if (lr) {
            assert rl : "lr without rl - if left side references right sources, then visa versa must be true";
            return OperatorNode.create(joinExpr.getLocation(), joinExpr.getAnnotations(),
                    joinExpr.getOperator(), rightExpr, leftExpr);
        }
        return joinExpr;
    }
    default:
        throw new ProgramCompileException(joinExpr.getLocation(),
                "Only EQ is a supported JOIN expression operator at this time (not %s)",
                joinExpr.getOperator());
    }
}

From source file:com.google.gitiles.RevisionServlet.java

static List<RevObject> listObjects(RevWalk walk, ObjectId id) throws MissingObjectException, IOException {
    List<RevObject> objects = Lists.newArrayListWithExpectedSize(1);
    while (true) {
        RevObject cur = walk.parseAny(id);
        objects.add(cur);// w  w w  .  j  a  va2 s.  co  m
        if (cur.getType() == Constants.OBJ_TAG) {
            id = ((RevTag) cur).getObject();
        } else {
            break;
        }
    }
    return objects;
}

From source file:org.apache.phoenix.mapreduce.index.PhoenixIndexPartialBuildMapper.java

@Override
protected void setup(final Context context) throws IOException, InterruptedException {
    super.setup(context);
    final Configuration configuration = context.getConfiguration();
    writer = new DirectHTableWriter(configuration);

    try {/*from  w  w w . j av a  2s.c om*/
        final Properties overrideProps = new Properties();
        String scn = configuration.get(PhoenixConfigurationUtil.CURRENT_SCN_VALUE);
        String txScnValue = configuration.get(PhoenixConfigurationUtil.TX_SCN_VALUE);
        if (txScnValue == null && scn != null) {
            overrideProps.put(PhoenixRuntime.CURRENT_SCN_ATTRIB, scn);
        }
        connection = ConnectionUtil.getOutputConnection(configuration, overrideProps)
                .unwrap(PhoenixConnection.class);
        connection.setAutoCommit(false);
        // Get BatchSize
        ConnectionQueryServices services = connection.getQueryServices();
        int maxSize = services.getProps().getInt(QueryServices.MAX_MUTATION_SIZE_ATTRIB,
                QueryServicesOptions.DEFAULT_MAX_MUTATION_SIZE);
        batchSize = Math.min(connection.getMutateBatchSize(), maxSize);
        LOG.info("Mutation Batch Size = " + batchSize);
        this.mutations = Lists.newArrayListWithExpectedSize(batchSize);
        maintainers = new ImmutableBytesPtr(PhoenixConfigurationUtil.getIndexMaintainers(configuration));
    } catch (SQLException e) {
        throw new RuntimeException(e.getMessage());
    }
}

From source file:org.apache.mahout.math.neighborhood.Searcher.java

public List<WeightedThing<Vector>> searchFirst(Iterable<? extends Vector> queries, boolean differentThanQuery) {
    List<WeightedThing<Vector>> results = Lists.newArrayListWithExpectedSize(Iterables.size(queries));
    for (Vector query : queries) {
        results.add(searchFirst(query, differentThanQuery));
    }//  ww  w.  j  a  va 2 s  .  c om
    return results;
}