Example usage for com.google.common.collect ImmutableList size

List of usage examples for com.google.common.collect ImmutableList size

Introduction

In this page you can find the example usage for com.google.common.collect ImmutableList size.

Prototype

int size();

Source Link

Document

Returns the number of elements in this list.

Usage

From source file:com.siemens.sw360.commonIO.TypeMappings.java

@NotNull
public static Map<Integer, Risk> getIntegerRiskMap(LicenseService.Iface licenseClient,
        Map<Integer, RiskCategory> riskCategoryMap, InputStream in) throws TException {
    List<CSVRecord> riskRecords = ImportCSV.readAsCSVRecords(in);
    final List<Risk> risksToAdd = ConvertRecord.convertRisks(riskRecords, riskCategoryMap);
    final List<Risk> risks = CommonUtils.nullToEmptyList(licenseClient.getRisks());
    Map<Integer, Risk> riskMap = Maps.newHashMap(Maps.uniqueIndex(risks, getRiskIdentifier()));
    final ImmutableList<Risk> filteredList = getElementsWithIdentifiersNotInMap(getRiskIdentifier(), riskMap,
            risksToAdd);/* ww  w .jav  a2  s.c o m*/
    List<Risk> addedRisks = null;
    if (filteredList.size() > 0) {
        addedRisks = licenseClient.addRisks(filteredList);
    }
    if (addedRisks != null)
        riskMap.putAll(Maps.uniqueIndex(addedRisks, getRiskIdentifier()));
    return riskMap;
}

From source file:com.facebook.buck.autodeps.AutodepsWriter.java

/**
 * Writes the {@code .autodeps} files in parallel using the {@code commandThreadManager}.
 * @param depsForBuildFiles Abstraction that contains the data that needs to be written to the
 *     {@code .autodeps} files./*w  w  w  .j av  a2s .  c  o m*/
 * @param buildFileName In practice, this should be derived from
 *     {@link com.facebook.buck.rules.Cell#getBuildFileName()}
 * @param includeSignature Whether to insert a signature for the contents of the file.
 * @param mapper To aid in JSON serialization.
 * @return the number of files that were written.
 */
public static int write(DepsForBuildFiles depsForBuildFiles, String buildFileName, boolean includeSignature,
        ObjectMapper mapper, ListeningExecutorService executorService, int numThreads)
        throws ExecutionException {
    Preconditions.checkArgument(numThreads > 0, "Must be at least one thread available");

    // We are going to divide the work into N groups, where N is the size of the thread pool.
    ImmutableList<DepsForBuildFiles.BuildFileWithDeps> buildFilesWithDeps = ImmutableList
            .copyOf(depsForBuildFiles);
    int numBuildFiles = buildFilesWithDeps.size();
    if (numBuildFiles == 0) {
        return 0;
    }
    int chunkSize = numBuildFiles / numThreads;
    int extraItems = numBuildFiles % numThreads;

    // Add the work to the executor. Note that instead of creating one future per build file, we
    // create one future per thread. This should reduce object allocation and context switching.
    List<ListenableFuture<Integer>> futures = new ArrayList<>();
    String autodepsFileName = buildFileName + GENERATED_BUILD_FILE_SUFFIX;
    for (int i = 0, endIndex = 0; i < numThreads; i++) {
        // Calculate how many items the thread should process.
        int numItemsToProcess = chunkSize;
        if (extraItems > 0) {
            numItemsToProcess++;
            extraItems--;
        }

        // Note that if buildFilesWithDeps.size() < numThreads, then this will be true for some
        // iterations of this loop.
        if (numItemsToProcess == 0) {
            break;
        }

        // Determine the subset of buildFilesWithDeps for the thread to process.
        int startIndex = endIndex;
        endIndex = startIndex + numItemsToProcess;
        ImmutableList<DepsForBuildFiles.BuildFileWithDeps> work = buildFilesWithDeps.subList(startIndex,
                endIndex);

        // Submit a job to the executor that will write .autodeps files, as appropriate. It will
        // return the number of .autodeps files it needed to write.
        ListenableFuture<Integer> future = executorService
                .submit(new AutodepsCallable(work, autodepsFileName, includeSignature, mapper));
        futures.add(future);
    }

    // Sum up the total number of files written from each worker.
    int totalWritten = 0;
    ListenableFuture<List<Integer>> futuresList = Futures.allAsList(futures);
    for (int numWritten : Uninterruptibles.getUninterruptibly(futuresList)) {
        totalWritten += numWritten;
    }
    return totalWritten;
}

From source file:com.siemens.sw360.commonIO.TypeMappings.java

@NotNull
public static <T, U> Map<U, T> getIdentifierToTypeMapAndWriteMissingToDatabase(
        LicenseService.Iface licenseClient, InputStream in, Class<T> clazz, Class<U> uClass) throws TException {
    Map<U, T> typeMap;/*  ww w  .j av  a  2  s .  c  o  m*/
    List<CSVRecord> records = ImportCSV.readAsCSVRecords(in);
    final List<T> recordsToAdd = simpleConvert(records, clazz);
    final List<T> fullList = CommonUtils.nullToEmptyList(getAllFromDB(licenseClient, clazz));
    typeMap = Maps.newHashMap(Maps.uniqueIndex(fullList, getIdentifier(clazz, uClass)));
    final ImmutableList<T> filteredList = getElementsWithIdentifiersNotInMap(getIdentifier(clazz, uClass),
            typeMap, recordsToAdd);
    List<T> added = null;
    if (filteredList.size() > 0) {
        added = addAlltoDB(licenseClient, clazz, filteredList);
    }
    if (added != null)
        typeMap.putAll(Maps.uniqueIndex(added, getIdentifier(clazz, uClass)));
    return typeMap;
}

From source file:org.apache.calcite.linq4j.Ord.java

/**
 * Iterates over a list in reverse order.
 *
 * <p>Given the list ["a", "b", "c"], returns (2, "c") then (1, "b") then
 * (0, "a")./*from w  ww .  ja v a2  s . c o  m*/
 */
public static <E> Iterable<Ord<E>> reverse(Iterable<? extends E> elements) {
    final ImmutableList<E> elementList = ImmutableList.copyOf(elements);
    return new Iterable<Ord<E>>() {
        public Iterator<Ord<E>> iterator() {
            return new Iterator<Ord<E>>() {
                int i = elementList.size() - 1;

                public boolean hasNext() {
                    return i >= 0;
                }

                public Ord<E> next() {
                    return Ord.of(i, elementList.get(i--));
                }

                public void remove() {
                    throw new UnsupportedOperationException("remove");
                }
            };
        }
    };
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.rules.HivePreFilteringRule.java

private static List<RexNode> extractCommonOperands(RexBuilder rexBuilder, RexNode condition,
        int maxCNFNodeCount) {
    assert condition.getKind() == SqlKind.OR;
    Multimap<String, RexNode> reductionCondition = LinkedHashMultimap.create();

    // Data structure to control whether a certain reference is present in every
    // operand/*from www  . java 2  s .  c o m*/
    Set<String> refsInAllOperands = null;

    // 1. We extract the information necessary to create the predicate for the
    // new filter; currently we support comparison functions, in and between
    ImmutableList<RexNode> operands = RexUtil.flattenOr(((RexCall) condition).getOperands());
    for (int i = 0; i < operands.size(); i++) {
        final RexNode operand = operands.get(i);

        final RexNode operandCNF = RexUtil.toCnf(rexBuilder, maxCNFNodeCount, operand);
        final List<RexNode> conjunctions = RelOptUtil.conjunctions(operandCNF);

        Set<String> refsInCurrentOperand = Sets.newHashSet();
        for (RexNode conjunction : conjunctions) {
            // We do not know what it is, we bail out for safety
            if (!(conjunction instanceof RexCall) || !HiveCalciteUtil.isDeterministic(conjunction)) {
                return new ArrayList<>();
            }
            RexCall conjCall = (RexCall) conjunction;
            RexNode ref = null;
            if (COMPARISON.contains(conjCall.getOperator().getKind())) {
                if (conjCall.operands.get(0) instanceof RexInputRef
                        && conjCall.operands.get(1) instanceof RexLiteral) {
                    ref = conjCall.operands.get(0);
                } else if (conjCall.operands.get(1) instanceof RexInputRef
                        && conjCall.operands.get(0) instanceof RexLiteral) {
                    ref = conjCall.operands.get(1);
                } else {
                    // We do not know what it is, we bail out for safety
                    return new ArrayList<>();
                }
            } else if (conjCall.getOperator().getKind().equals(SqlKind.IN)) {
                ref = conjCall.operands.get(0);
            } else if (conjCall.getOperator().getKind().equals(SqlKind.BETWEEN)) {
                ref = conjCall.operands.get(1);
            } else {
                // We do not know what it is, we bail out for safety
                return new ArrayList<>();
            }

            String stringRef = ref.toString();
            reductionCondition.put(stringRef, conjCall);
            refsInCurrentOperand.add(stringRef);
        }

        // Updates the references that are present in every operand up till now
        if (i == 0) {
            refsInAllOperands = refsInCurrentOperand;
        } else {
            refsInAllOperands = Sets.intersection(refsInAllOperands, refsInCurrentOperand);
        }
        // If we did not add any factor or there are no common factors, we can
        // bail out
        if (refsInAllOperands.isEmpty()) {
            return new ArrayList<>();
        }
    }

    // 2. We gather the common factors and return them
    List<RexNode> commonOperands = new ArrayList<>();
    for (String ref : refsInAllOperands) {
        commonOperands.add(RexUtil.composeDisjunction(rexBuilder, reductionCondition.get(ref), false));
    }
    return commonOperands;
}

From source file:org.geogit.geotools.plumbing.ExportDiffOp.java

private static Iterator<SimpleFeature> getFeatures(Iterator<DiffEntry> diffs, final boolean old,
        final ObjectDatabase database, final ObjectId metadataId, final ProgressListener progressListener) {

    final SimpleFeatureType featureType = addFidAttribute(database.getFeatureType(metadataId));
    final RevFeatureType revFeatureType = RevFeatureType.build(featureType);
    final SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder(featureType);

    Function<DiffEntry, SimpleFeature> asFeature = new Function<DiffEntry, SimpleFeature>() {

        @Override/*w  w w  . j  a  va  2s.  c  o  m*/
        @Nullable
        public SimpleFeature apply(final DiffEntry input) {
            NodeRef nodeRef = old ? input.getOldObject() : input.getNewObject();
            if (nodeRef == null) {
                return null;
            }
            final RevFeature revFeature = database.getFeature(nodeRef.objectId());
            ImmutableList<Optional<Object>> values = revFeature.getValues();
            for (int i = 0; i < values.size(); i++) {
                String name = featureType.getDescriptor(i + 1).getLocalName();
                Object value = values.get(i).orNull();
                featureBuilder.set(name, value);
            }
            featureBuilder.set("geogit_fid", nodeRef.name());
            Feature feature = featureBuilder.buildFeature(nodeRef.name());
            feature.getUserData().put(Hints.USE_PROVIDED_FID, true);
            feature.getUserData().put(RevFeature.class, revFeature);
            feature.getUserData().put(RevFeatureType.class, revFeatureType);

            if (feature instanceof SimpleFeature) {
                return (SimpleFeature) feature;
            }
            return null;
        }

    };

    Iterator<SimpleFeature> asFeatures = Iterators.transform(diffs, asFeature);

    UnmodifiableIterator<SimpleFeature> filterNulls = Iterators.filter(asFeatures, Predicates.notNull());

    return filterNulls;
}

From source file:com.google.devtools.build.benchmark.BuildGroupRunner.java

private static void prepareBuildEnvConfigs(ImmutableList<BuildEnvConfig> buildEnvConfigs,
        BuildTargetResult.Builder targetBuilder, ImmutableList<String> codeVersions,
        ImmutableList<String> datetimes) {
    for (BuildEnvConfig envConfig : buildEnvConfigs) {
        BuildEnvResult.Builder envBuilder = BuildEnvResult.newBuilder().setConfig(envConfig);
        for (int i = 0; i < codeVersions.size(); ++i) {
            envBuilder.addResults(SingleBuildResult.newBuilder().setCodeVersion(codeVersions.get(i))
                    .setDatetime(datetimes.get(i)).build());
        }/*from   www.  j av a2 s .  c  om*/
        targetBuilder.addBuildEnvResults(envBuilder.build());
    }
}

From source file:org.apache.hadoop.hive.ql.optimizer.calcite.cost.HiveAlgorithmsUtil.java

public static double computeSMBMapJoinCPUCost(ImmutableList<Double> cardinalities) {
    // Hash-join/*from w ww.j  ava 2 s . c om*/
    double cpuCost = 0.0;
    for (int i = 0; i < cardinalities.size(); i++) {
        cpuCost += cardinalities.get(i) * cpuCost;
    }
    return cpuCost;
}

From source file:de.metas.ui.web.window.descriptor.filters.CompositeDocumentFilterDescriptorsProvider.java

public static DocumentFilterDescriptorsProvider compose(final DocumentFilterDescriptorsProvider... providers) {
    if (providers == null || providers.length <= 0) {
        return NullDocumentFilterDescriptorsProvider.instance;
    }//from  w ww .jav a2  s.  co  m

    final ImmutableList<DocumentFilterDescriptorsProvider> providersList = Stream.of(providers)
            .filter(provider -> !NullDocumentFilterDescriptorsProvider.isNull(provider))
            .collect(GuavaCollectors.toImmutableList());

    if (providersList.isEmpty()) {
        return NullDocumentFilterDescriptorsProvider.instance;
    } else if (providersList.size() == 1) {
        return providersList.get(0);
    }

    return new CompositeDocumentFilterDescriptorsProvider(providersList);
}

From source file:com.google.testing.util.MoreAsserts.java

/**
 * Asserts that {@code actual} contains precisely the elements
 * {@code expected}, in any order.  Both collections may contain
 * duplicates, and this method will only pass if the quantities are
 * exactly the same.  This method uses the user-provided Comparator
 * object for doing the object comparison, instead of relying on the
 * contents' implementation of {@link Object#equals(Object)}. It also takes
 * in the expected set of objects as an Iterable.
 * <p>//ww  w  .  j  a v a2s  . c o m
 * Note the different order of expected and actual from the other
 * {@link #assertContentsAnyOrder(String,Iterable,Object...)}
 */
public static <T> void assertContentsAnyOrder(String message, Iterable<? extends T> expected,
        Iterable<? extends T> actual, Comparator<? super T> comparator) {
    // We should not iterate over an Iterable more than once. There's
    // no guarentees that Iterable.iterator() returns an iterator over the
    // entire collection every time.
    //
    // Why don't we use TreeMultiset? Unfortunately, TreeMultiset.toString()
    // produces really odd output for duplicates. In addition, our contract
    // states that we use the comparator to compare equality, not to order
    // items.
    ImmutableList<T> actualList = ImmutableList.copyOf(actual);
    ImmutableList<T> expectedList = ImmutableList.copyOf(expected);

    // First compare sizes to save ourselves on N X M operation.
    // This also handles the case where "expected" is a subset of "actual".
    if (actualList.size() != expectedList.size()) {
        failNotEqual(message, expectedList, actualList);
    }

    // Now for each expected value, iterate through actuals and delete entry
    // if found. We need to make another copy of the "actual" items because
    // we will be removing items from this list, and we need to keep the original
    // for the failure message.
    List<T> unfoundItems = Lists.newLinkedList(actualList);
    for (T ex : expectedList) {
        boolean found = false;
        Iterator<T> iter = unfoundItems.iterator();
        while (iter.hasNext()) {
            T ac = iter.next();
            if (comparator.compare(ex, ac) == 0) {
                iter.remove();
                found = true;
                break;
            }
        }
        if (!found) {
            failNotEqual(message, expectedList, actualList);
        }
    }
}