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:org.icgc.dcc.release.job.document.function.PairGeneIdObservation.java

@Override
public Iterable<Tuple2<String, Occurrence>> call(Occurrence observation) throws Exception {
    val uniqueGeneIds = Sets.newHashSet(getObservationConsequenceGeneIds(observation));
    List<Tuple2<String, Occurrence>> values = Lists.newArrayListWithCapacity(uniqueGeneIds.size());
    for (val observationGeneId : uniqueGeneIds) {
        if (observationGeneId != null) {
            values.add(tuple(observationGeneId, observation));
        }//from  ww  w.  j a va2s  .  co  m
    }

    return values;
}

From source file:org.apache.drill.exec.planner.common.DrillRelOptUtil.java

public static boolean areRowTypesCompatible(RelDataType rowType1, RelDataType rowType2, boolean compareNames,
        boolean allowSubstring) {
    if (rowType1 == rowType2) {
        return true;
    }/*  w  w w. ja  v  a  2 s.c  o m*/
    if (compareNames) {
        // if types are not identity-equal, then either the names or
        // the types must be different
        return false;
    }
    if (rowType2.getFieldCount() != rowType1.getFieldCount()) {
        return false;
    }
    final List<RelDataTypeField> f1 = rowType1.getFieldList();
    final List<RelDataTypeField> f2 = rowType2.getFieldList();
    for (Pair<RelDataTypeField, RelDataTypeField> pair : Pair.zip(f1, f2)) {
        final RelDataType type1 = pair.left.getType();
        final RelDataType type2 = pair.right.getType();
        // If one of the types is ANY comparison should succeed
        if (type1.getSqlTypeName() == SqlTypeName.ANY || type2.getSqlTypeName() == SqlTypeName.ANY) {
            continue;
        }
        if (type1.getSqlTypeName() != type2.getSqlTypeName()) {
            if (allowSubstring
                    && (type1.getSqlTypeName() == SqlTypeName.CHAR
                            && type2.getSqlTypeName() == SqlTypeName.CHAR)
                    && (type1.getPrecision() <= type2.getPrecision())) {
                return true;
            }

            // Check if Drill implicit casting can resolve the incompatibility
            List<TypeProtos.MinorType> types = Lists.newArrayListWithCapacity(2);
            types.add(Types.getMinorTypeFromName(type1.getSqlTypeName().getName()));
            types.add(Types.getMinorTypeFromName(type2.getSqlTypeName().getName()));
            if (TypeCastRules.getLeastRestrictiveType(types) != null) {
                return true;
            }

            return false;
        }
    }
    return true;
}

From source file:fr.univnantes.lina.uima.tkregex.RegexOccurrence.java

RegexOccurrence(Automaton automaton, Iterable<LabelledAnnotation> list) {
    super();//from w w  w . j a va  2 s .co m
    this.automaton = automaton;
    this.allMatchingAnnotations = ImmutableList.copyOf(list);
    this.labelledAnnotations = ImmutableList.copyOf(labelledAnnotationIterator());
    this.size = this.labelledAnnotations.size();
    if (size > 0) {
        this.last = this.labelledAnnotations.get(size - 1);
        this.begin = this.labelledAnnotations.get(0).getAnnotation().getBegin();
        this.end = this.last.getAnnotation().getEnd();
    }
    this.labels = Lists.newArrayListWithCapacity(this.size);
    final Iterator<LabelledAnnotation> it = this.labelledAnnotations.iterator();
    while (it.hasNext()) {
        LabelledAnnotation la = it.next();
        labels.add(la.getLabel() == null ? la.getAnnotation().getCoveredText() : la.getLabel());
    }
    if (end < begin)
        throw new IllegalArgumentException("end < begin");
}

From source file:de.craftolution.craftoplugin4.modules.web.common.TCPPacket.java

public TCPPacket(String string) {
    String[] rawParts = string.split('\\' + DELIMITER);
    this.id = Integer.parseInt(rawParts[0]);
    this.responseId = Integer.parseInt(rawParts[1]);
    this.type = PacketType.getById(rawParts[2]).get();
    this.data = Lists.newArrayListWithCapacity(rawParts.length - 3);

    for (int i = 3; i < rawParts.length; i++) {
        this.data.add(rawParts[i]);
    }/*  w ww  .ja  v  a  2  s .  c  o m*/
}

From source file:org.elasticsearch.search.fetch.matchedqueries.MatchedQueriesFetchSubPhase.java

@Override
public void hitExecute(SearchContext context, HitContext hitContext) throws ElasticsearchException {
    List<String> matchedQueries = Lists.newArrayListWithCapacity(2);

    addMatchedQueries(hitContext, context.parsedQuery().namedFilters(), matchedQueries);

    if (context.parsedPostFilter() != null) {
        addMatchedQueries(hitContext, context.parsedPostFilter().namedFilters(), matchedQueries);
    }//from  w w  w  . j av a2s  .c o m

    hitContext.hit().matchedQueries(matchedQueries.toArray(new String[matchedQueries.size()]));
}

From source file:org.eclipse.xtext.common.types.access.binary.asm.AbstractBinarySignature.java

protected List<BinaryTypeParameter> doGetTypeParameters() {
    try {/* ww  w .  jav a2 s . c  o  m*/
        int length = this.length;
        if (length == 0)
            return Collections.emptyList();
        if (chars.charAt(offset) != '<')
            return Collections.emptyList();

        List<BinaryTypeParameter> result = Lists.newArrayListWithCapacity(2);
        int paramStart = offset + 1, i = offset + 1; // start after leading '<'
        while (i < length) {
            if (chars.charAt(i) == '>') {
                return result;
            }
            i = chars.indexOf(':', i);
            if (i < 0 || i >= length)
                throw new IllegalArgumentException();
            // iterate over bounds
            while (chars.charAt(i) == ':') {
                i++; // skip colon
                switch (chars.charAt(i)) {
                case ':':
                    // no class bound
                    break;
                case '>':
                    break;
                case 'L':
                case '[':
                case 'T':
                    try {
                        i = SignatureUtil.scanTypeSignature(chars, i);
                        i++; // position at start of next param if any
                    } catch (IllegalArgumentException e) {
                        // not a class type signature -> it is a new type parameter
                    }
                    break;
                // default: another type parameter is starting
                }
            }
            result.add(new BinaryTypeParameter(chars, paramStart, i - paramStart));
            paramStart = i; // next param start from here
        }
    } catch (ArrayIndexOutOfBoundsException e) {
        // invalid signature, fall through
    }
    throw new IllegalArgumentException();
}

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

@Nullable
public LightweightMergedBoundTypeArgument merge(Collection<LightweightBoundTypeArgument> allArguments,
        ITypeReferenceOwner owner) {//from w ww .j av a 2  s .  c o  m
    if (allArguments.isEmpty())
        return null;
    if (allArguments.size() == 1) {
        LightweightBoundTypeArgument argument = Iterables.getOnlyElement(allArguments);
        return getSingleArgumentAsMergedArgument(argument);
    }
    List<LightweightTypeReference> invariantTypes = Lists.newArrayListWithCapacity(3);
    List<VarianceInfo> invariantVariances = Lists.newArrayListWithCapacity(3);
    List<LightweightTypeReference> outTypes = Lists.newArrayListWithCapacity(3);
    List<LightweightTypeReference> constraintOutTypes = Lists.newArrayListWithCapacity(3);
    List<VarianceInfo> outVariances = Lists.newArrayListWithCapacity(3);
    List<LightweightTypeReference> inTypes = Lists.newArrayListWithCapacity(3);
    List<VarianceInfo> inVariances = Lists.newArrayListWithCapacity(3);
    Set<Object> seenOrigin = Sets.newHashSet();
    for (LightweightBoundTypeArgument boundTypeArgument : allArguments) {
        Object origin = boundTypeArgument.getOrigin();
        switch (boundTypeArgument.getDeclaredVariance()) {
        case INVARIANT:
            invariantTypes.add(boundTypeArgument.getTypeReference());
            if (seenOrigin.add(origin) || origin == null || boundTypeArgument.isValidVariancePair()) {
                invariantVariances.add(boundTypeArgument.getActualVariance());
            }
            break;
        case OUT:
            if (boundTypeArgument.getSource() == BoundTypeArgumentSource.CONSTRAINT) {
                constraintOutTypes.add(boundTypeArgument.getTypeReference());
            } else {
                outTypes.add(boundTypeArgument.getTypeReference());
            }
            if (seenOrigin.add(origin) || origin == null || boundTypeArgument.isValidVariancePair()) {
                outVariances.add(boundTypeArgument.getActualVariance());
            }
            break;
        case IN:
            inTypes.add(boundTypeArgument.getTypeReference());
            if (seenOrigin.add(origin) || origin == null || boundTypeArgument.isValidVariancePair()) {
                inVariances.add(boundTypeArgument.getActualVariance());
            }
            break;
        }
    }
    LightweightTypeReference type = null;
    VarianceInfo variance = null;
    if (outTypes.isEmpty()) {
        outTypes.addAll(constraintOutTypes);
    }
    if (!invariantTypes.isEmpty()) {
        type = invariantTypes.get(0);
        variance = VarianceInfo.INVARIANT.mergeDeclaredWithActuals(invariantVariances);
        if (variance == null && invariantVariances.contains(VarianceInfo.IN) && invariantTypes.size() > 1) {
            TypeConformanceComputer conformanceComputer = owner.getServices().getTypeConformanceComputer();
            type = conformanceComputer.getCommonSuperType(invariantTypes, owner);
        }
        if (!outVariances.isEmpty()) {
            VarianceInfo outVariance = VarianceInfo.OUT.mergeDeclaredWithActuals(outVariances);
            variance = VarianceInfo.OUT.mergeInvariance(variance, outVariance);
        } else if (!inVariances.isEmpty()) {
            VarianceInfo inVariance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
            variance = VarianceInfo.IN.mergeInvariance(variance, inVariance);
        }
    } else if (!outTypes.isEmpty()) {
        TypeConformanceComputer conformanceComputer = owner.getServices().getTypeConformanceComputer();
        type = conformanceComputer.getCommonSuperType(outTypes, owner);
        if (type == null)
            throw new IllegalStateException("common super type may not be null");
        variance = VarianceInfo.OUT.mergeDeclaredWithActuals(outVariances);
        if (!inVariances.isEmpty()) {
            LightweightTypeReference inType = getMostSpecialType(inTypes);
            boolean conformant = type.isAssignableFrom(inType,
                    new TypeConformanceComputationArgument(false, true, false, false, true, false));
            if (conformant) {
                VarianceInfo inVariance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
                variance = VarianceInfo.IN.mergeWithOut(variance, inVariance, conformant);
            } else {
                boolean reverseConformant = inType.isAssignableFrom(type,
                        new TypeConformanceComputationArgument(false, false, false, false, true, false));
                if (reverseConformant && variance == VarianceInfo.INVARIANT
                        && VarianceInfo.IN.mergeDeclaredWithActuals(inVariances) == VarianceInfo.INVARIANT) {
                    if (VarianceInfo.IN.mergeDeclaredWithActuals(outVariances) != null) {
                        type = inType;
                        variance = VarianceInfo.OUT;
                    }
                } else {
                    VarianceInfo inVariance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
                    variance = VarianceInfo.IN.mergeWithOut(variance, inVariance, conformant);
                }
            }
        }
    } else if (!inTypes.isEmpty()) {
        type = getMostSpecialType(inTypes);
        variance = VarianceInfo.IN.mergeDeclaredWithActuals(inVariances);
    }
    return new LightweightMergedBoundTypeArgument(type, variance);
}

From source file:co.cask.tigon.data.transaction.queue.inmemory.InMemoryQueue.java

public ImmutablePair<List<Key>, List<byte[]>> dequeue(Transaction tx, ConsumerConfig config,
        ConsumerState consumerState, int maxBatchSize) {

    List<Key> keys = Lists.newArrayListWithCapacity(maxBatchSize);
    List<byte[]> datas = Lists.newArrayListWithCapacity(maxBatchSize);
    NavigableSet<Key> keysToScan = consumerState.startKey == null ? entries.navigableKeySet()
            : entries.tailMap(consumerState.startKey).navigableKeySet();
    boolean updateStartKey = true;

    // navigableKeySet is immune to concurrent modification
    for (Key key : keysToScan) {
        if (keys.size() >= maxBatchSize) {
            break;
        }/*from  www.  jav a  2  s  .c om*/
        if (updateStartKey && key.txId < tx.getFirstShortInProgress()) {
            // See QueueEntryRow#canCommit for reason.
            consumerState.startKey = key;
        }
        if (tx.getReadPointer() < key.txId) {
            // the entry is newer than the current transaction. so are all subsequent entries. bail out.
            break;
        } else if (tx.isInProgress(key.txId)) {
            // the entry is in the exclude list of current transaction. There is a chance that visible entries follow.
            updateStartKey = false; // next time we have to revisit this entry
            continue;
        }
        Item item = entries.get(key);
        if (item == null) {
            // entry was deleted (evicted or undone) after we started iterating
            continue;
        }
        // check whether this is processed already
        ConsumerEntryState state = item.getConsumerState(config.getGroupId());
        if (ConsumerEntryState.PROCESSED.equals(state)) {
            // already processed but not yet evicted. move on
            continue;
        }
        if (config.getDequeueStrategy().equals(DequeueStrategy.FIFO)) {
            // for FIFO, attempt to claim the entry and return it
            if (item.claim(config)) {
                keys.add(key);
                datas.add(item.entry.getData());
            }
            // else: someone else claimed it, or it was already processed, move on, but we may have to revisit this.
            updateStartKey = false;
            continue;
        }
        // for hash/round robin, if group size is 1, just take it
        if (config.getGroupSize() == 1) {
            keys.add(key);
            datas.add(item.entry.getData());
            updateStartKey = false;
            continue;
        }
        // hash by entry hash key or entry id
        int hash;
        if (config.getDequeueStrategy().equals(DequeueStrategy.ROUND_ROBIN)) {
            hash = key.hashCode();
        } else {
            Integer hashFoundInEntry = item.entry.getHashKey(config.getHashKey());
            hash = hashFoundInEntry == null ? 0 : hashFoundInEntry;
        }
        // modulo of a negative is negative, make sure we're positive or 0.
        if (Math.abs(hash) % config.getGroupSize() == config.getInstanceId()) {
            keys.add(key);
            datas.add(item.entry.getData());
            updateStartKey = false;
        }
    }
    return keys.isEmpty() ? null : ImmutablePair.of(keys, datas);
}

From source file:com.opengamma.web.server.push.rest.json.ViewportResultsMessageBodyWriter.java

@Override
public void writeTo(ViewportResults results, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    // TODO move this to a JSON writer class
    List<List<ViewportResults.Cell>> viewportCells = results.getResults();
    List<List<Object>> allResults = Lists.newArrayListWithCapacity(viewportCells.size());
    for (List<ViewportResults.Cell> rowCells : viewportCells) {
        List<Object> rowResults = Lists.newArrayListWithCapacity(rowCells.size());
        int viewportColIndex = 0;
        for (ViewportResults.Cell cell : rowCells) {
            Object formattedValue;
            Object cellValue = cell.getValue();
            ValueSpecification cellValueSpec = cell.getValueSpecification();
            if (results.isExpanded()) {
                formattedValue = _formatter.formatForExpandedDisplay(cellValue, cellValueSpec);
            } else {
                formattedValue = _formatter.formatForDisplay(cellValue, cellValueSpec);
            }/*  w  ww.j a  v a 2 s.c o m*/
            Collection<Object> history = cell.getHistory();
            Class<?> columnType = results.getColumnType(viewportColIndex++);

            if (columnType == null || history != null) {
                // if there is history or we need to send type info then we need to send an object, not just the value
                Map<String, Object> valueMap = Maps.newHashMap();
                valueMap.put(VALUE_KEY, formattedValue);
                // if the the column type isn't known then send the type with the value
                if (columnType == null) {
                    Class<?> cellValueClass = cellValue == null ? null : cellValue.getClass();
                    valueMap.put(TYPE_KEY, _formatter.getFormatType(cellValueClass).name());
                }
                if (history != null) {
                    List<Object> formattedHistory = Lists.newArrayListWithCapacity(history.size());
                    for (Object historyValue : history) {
                        formattedHistory.add(_formatter.formatForHistory(historyValue, cellValueSpec));
                    }
                    valueMap.put(HISTORY_KEY, formattedHistory);
                }
                rowResults.add(valueMap);
            } else {
                rowResults.add(formattedValue);
            }
        }
        allResults.add(rowResults);
    }
    ImmutableMap<String, Object> resultsMap = ImmutableMap.of(ViewportVersionMessageBodyWriter.VERSION,
            results.getVersion(), DATA, allResults);
    entityStream.write(new JSONObject(resultsMap).toString().getBytes());
}

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

public LazyTypeArgumentContext() {
    this.delegates = Lists.newArrayListWithCapacity(3);
}