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

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

Introduction

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

Prototype

default Stream<E> stream() 

Source Link

Document

Returns a sequential Stream with this collection as its source.

Usage

From source file:com.facebook.buck.cli.PublishCommand.java

@Override
public ImmutableList<TargetNodeSpec> parseArgumentsAsTargetNodeSpecs(BuckConfig config,
        Iterable<String> targetsAsArgs) {
    ImmutableList<TargetNodeSpec> specs = super.parseArgumentsAsTargetNodeSpecs(config, targetsAsArgs);

    if (includeSource) {
        specs = ImmutableList.<TargetNodeSpec>builder().addAll(specs).addAll(specs.stream().filter(input -> {
            if (!(input instanceof BuildTargetSpec)) {
                throw new IllegalArgumentException(
                        "Targets must be explicitly defined when using " + INCLUDE_SOURCE_LONG_ARG);
            }//from   ww w .j  a  va  2  s.com
            return !((BuildTargetSpec) input).getBuildTarget().getFlavors().contains(JavaLibrary.SRC_JAR);
        }).map(input -> BuildTargetSpec.of(
                ((BuildTargetSpec) input).getBuildTarget().withFlavors(JavaLibrary.SRC_JAR),
                input.getBuildFileSpec())).iterator()).build();
    }

    // Append "maven" flavor
    specs = specs.stream().map(input -> {
        if (!(input instanceof BuildTargetSpec)) {
            throw new IllegalArgumentException(
                    "Need to specify build targets explicitly when publishing. " + "Cannot modify " + input);
        }
        BuildTargetSpec buildTargetSpec = (BuildTargetSpec) input;
        BuildTarget buildTarget = Preconditions.checkNotNull(buildTargetSpec.getBuildTarget());
        return buildTargetSpec
                .withBuildTarget(BuildTarget.builder(buildTarget).addFlavors(JavaLibrary.MAVEN_JAR).build());
    }).collect(MoreCollectors.toImmutableList());

    return specs;
}

From source file:com.google.errorprone.bugpatterns.argumentselectiondefects.Costs.java

Changes computeAssignments() {
    int[] assignments = new HungarianAlgorithm(costMatrix).execute();
    ImmutableList<Parameter> formalsWithChange = formals.stream()
            .filter(f -> assignments[f.index()] != f.index()).collect(toImmutableList());

    if (formalsWithChange.isEmpty()) {
        return Changes.empty();
    }/*  w  w w.  ja v a  2 s . c  o  m*/

    ImmutableList<Double> originalCost = formalsWithChange.stream()
            .map(f2 -> costMatrix[f2.index()][f2.index()]).collect(toImmutableList());

    ImmutableList<Double> assignmentCost = formalsWithChange.stream()
            .map(f1 -> costMatrix[f1.index()][assignments[f1.index()]]).collect(toImmutableList());

    ImmutableList<ParameterPair> changes = formalsWithChange.stream()
            .map(f -> ParameterPair.create(f, actuals.get(assignments[f.index()]))).collect(toImmutableList());

    return Changes.create(originalCost, assignmentCost, changes);
}

From source file:com.spectralogic.ds3autogen.java.generators.responsemodels.RetryAfterResponseGenerator.java

/**
 * Retrieves the arguments: response payload, retry after seconds, and status
 *//*  w  ww. j a  v  a2  s  .  c o  m*/
@Override
public ImmutableList<Arguments> toParamList(final ImmutableList<Ds3ResponseCode> ds3ResponseCodes) {
    final ImmutableList.Builder<Arguments> builder = ImmutableList.builder();
    builder.add(new Arguments("int", "RetryAfterSeconds"));
    builder.add(new Arguments("Status", "Status"));

    if (hasContent(ds3ResponseCodes)) {
        final ImmutableList<Arguments> responseCodeArgs = ds3ResponseCodes.stream()
                .filter(i -> i.getCode() < ERROR_CODE_THRESHOLD) //Filter error codes
                .map(BaseResponseGenerator::toParam).filter(Optional::isPresent) //Filters out empty optional arguments
                .map(Optional::get) //Get the Arguments object out of the optional
                .collect(GuavaCollectors.immutableList());

        builder.addAll(responseCodeArgs);
    }

    return builder.build().stream().sorted(new CustomArgumentComparator()) //Sorts the arguments by name
            .collect(GuavaCollectors.immutableList());
}

From source file:com.google.errorprone.names.TermEditDistance.java

public double getNormalizedEditDistance(String source, String target) {

    ImmutableList<String> sourceTerms = NamingConventions.splitToLowercaseTerms(source);
    ImmutableList<String> targetTerms = NamingConventions.splitToLowercaseTerms(target);

    // costMatrix[s][t] is the edit distance between source term s and target term t
    double[][] costMatrix = sourceTerms.stream()
            .map(s -> targetTerms.stream().mapToDouble(t -> editDistanceFn.apply(s, t)).toArray())
            .toArray(double[][]::new);

    // worstCaseMatrix[s][t] is the worst case distance between source term s and target term t
    double[][] worstCaseMatrix = sourceTerms.stream().map(s -> s.length()).map(s -> targetTerms.stream()
            .map(t -> t.length()).mapToDouble(t -> maxDistanceFn.apply(s, t)).toArray())
            .toArray(double[][]::new);

    double[] sourceTermDeletionCosts = sourceTerms.stream().mapToDouble(s -> maxDistanceFn.apply(s.length(), 0))
            .toArray();//w  w w.j  a v  a 2  s.c om

    double[] targetTermAdditionCosts = targetTerms.stream().mapToDouble(s -> maxDistanceFn.apply(0, s.length()))
            .toArray();

    // this is an array of assignments of source terms to target terms. If assignments[i] contains
    // the value j this means that source term i has been assigned to target term j
    // There will be one entry in cost for each source term:
    // - If there are more source terms than target terms then some will be unassigned - value -1
    // - If there are a fewer source terms than target terms then some target terms will not be
    //    referenced in the array
    int[] assignments = new HungarianAlgorithm(costMatrix).execute();
    double assignmentCost = computeCost(assignments, costMatrix, sourceTermDeletionCosts,
            targetTermAdditionCosts);

    double maxCost = computeCost(assignments, worstCaseMatrix, sourceTermDeletionCosts,
            targetTermAdditionCosts);

    return assignmentCost / maxCost;
}

From source file:com.google.devtools.build.lib.rules.cpp.FeatureSelection.java

/**
 * @return a {@link FeatureConfiguration} that reflects the set of activated features and action
 *     configs./*from  w  ww.j  a  va  2  s  .  c o  m*/
 */
FeatureConfiguration run() throws CollidingProvidesException {
    for (CrosstoolSelectable selectable : requestedSelectables) {
        enableAllImpliedBy(selectable);
    }

    disableUnsupportedActivatables();
    ImmutableList.Builder<CrosstoolSelectable> enabledActivatablesInOrderBuilder = ImmutableList.builder();
    for (CrosstoolSelectable selectable : selectables) {
        if (enabled.contains(selectable)) {
            enabledActivatablesInOrderBuilder.add(selectable);
        }
    }

    ImmutableList<CrosstoolSelectable> enabledActivatablesInOrder = enabledActivatablesInOrderBuilder.build();
    ImmutableList<Feature> enabledFeaturesInOrder = enabledActivatablesInOrder.stream()
            .filter(a -> a instanceof Feature).map(f -> (Feature) f).collect(ImmutableList.toImmutableList());
    Iterable<ActionConfig> enabledActionConfigsInOrder = Iterables.filter(enabledActivatablesInOrder,
            ActionConfig.class);

    for (String provided : provides.keys()) {
        List<String> conflicts = new ArrayList<>();
        for (CrosstoolSelectable selectableProvidingString : provides.get(provided)) {
            if (enabledActivatablesInOrder.contains(selectableProvidingString)) {
                conflicts.add(selectableProvidingString.getName());
            }
        }

        if (conflicts.size() > 1) {
            throw new CollidingProvidesException(String.format(CcToolchainFeatures.COLLIDING_PROVIDES_ERROR,
                    provided, Joiner.on(" ").join(conflicts)));
        }
    }

    ImmutableSet.Builder<String> enabledActionConfigNames = ImmutableSet.builder();
    for (ActionConfig actionConfig : enabledActionConfigsInOrder) {
        enabledActionConfigNames.add(actionConfig.getActionName());
    }

    return new FeatureConfiguration(enabledFeaturesInOrder, enabledActionConfigNames.build(),
            actionConfigsByActionName);
}

From source file:com.facebook.buck.jvm.java.ExternalJavac.java

private ImmutableList<Path> getExpandedSourcePaths(ProjectFilesystem projectFilesystem,
        BuildTarget invokingRule, ImmutableSet<Path> javaSourceFilePaths, Optional<Path> workingDirectory)
        throws IOException {

    // Add sources file or sources list to command
    ImmutableList.Builder<Path> sources = ImmutableList.builder();
    for (Path path : javaSourceFilePaths) {
        String pathString = path.toString();
        if (pathString.endsWith(".java")) {
            sources.add(path);/*w ww .  ja  va 2 s  .  c o  m*/
        } else if (pathString.endsWith(SRC_ZIP) || pathString.endsWith(SRC_JAR)) {
            if (!workingDirectory.isPresent()) {
                throw new HumanReadableException(
                        "Attempting to compile target %s which specified a .src.zip input %s but no "
                                + "working directory was specified.",
                        invokingRule.toString(), path);
            }
            // For a Zip of .java files, create a JavaFileObject for each .java entry.
            ImmutableList<Path> zipPaths = Unzip.extractZipFile(projectFilesystem.resolve(path),
                    projectFilesystem.resolve(workingDirectory.get()), Unzip.ExistingFileMode.OVERWRITE);
            sources.addAll(zipPaths.stream().filter(input -> input.toString().endsWith(".java")).iterator());
        }
    }
    return sources.build();
}

From source file:com.opengamma.strata.collect.io.CsvFile.java

/**
 * Restricted constructor./*from  ww w . j  av a2 s .  c om*/
 * 
 * @param headers  the header row
 * @param rows  the data rows
 */
private CsvFile(ImmutableList<String> headers, ImmutableMap<String, Integer> searchHeaders,
        ImmutableList<ImmutableList<String>> rows) {

    this.headers = headers;
    this.searchHeaders = searchHeaders;
    this.rows = rows.stream().map(cols -> new CsvRow(headers, this.searchHeaders, cols))
            .collect(toImmutableList());
}

From source file:com.facebook.buck.jvm.java.DefaultSourceOnlyAbiRuleInfo.java

public DefaultSourceOnlyAbiRuleInfo(ImmutableList<JavaDependencyInfo> classPathInfo,
        JavaFileManager fileManager, BuildTarget buildTarget, boolean ruleIsRequiredForSourceOnlyAbi) {

    this.buildTarget = buildTarget;
    this.ruleIsRequiredForSourceOnlyAbi = ruleIsRequiredForSourceOnlyAbi;
    this.fileManager = fileManager;

    fullJarInfos = classPathInfo.stream().map(info -> new DefaultJavaAbiInfo(info.compileTimeJar))
            .collect(ImmutableList.toImmutableList());

    abiJarInfos = classPathInfo.stream().filter(info -> info.isRequiredForSourceOnlyAbi)
            .map(info -> new DefaultJavaAbiInfo(info.compileTimeJar)).collect(ImmutableList.toImmutableList());
}

From source file:com.google.errorprone.bugpatterns.AnnotationPosition.java

/** Checks that annotations are on the right side of the modifiers. */
private Description checkAnnotations(Tree tree, int treePos, List<? extends AnnotationTree> annotations,
        Comment danglingJavadoc, int firstModifierPos, int lastModifierPos, VisitorState state) {
    SuggestedFix.Builder builder = SuggestedFix.builder();
    List<AnnotationTree> moveBefore = new ArrayList<>();
    List<AnnotationTree> moveAfter = new ArrayList<>();

    boolean annotationProblem = false;
    for (AnnotationTree annotation : annotations) {
        int annotationPos = ((JCTree) annotation).getStartPosition();
        if (annotationPos <= firstModifierPos) {
            continue;
        }/*  w  w  w  . j  av  a2s  .com*/
        AnnotationType annotationType = ASTHelpers.getAnnotationType(annotation, getSymbol(tree), state);
        if (annotationPos >= lastModifierPos) {
            if (tree instanceof ClassTree || annotationType == AnnotationType.DECLARATION) {
                annotationProblem = true;
                moveBefore.add(annotation);
            }
        } else {
            annotationProblem = true;
            if (tree instanceof ClassTree || annotationType == AnnotationType.DECLARATION
                    || annotationType == null) {
                moveBefore.add(annotation);
            } else {
                moveAfter.add(annotation);
            }
        }
    }
    if (annotationProblem) {
        for (AnnotationTree annotation : moveBefore) {
            builder.delete(annotation);
        }
        for (AnnotationTree annotation : moveAfter) {
            builder.delete(annotation);
        }
        String javadoc = danglingJavadoc == null ? "" : removeJavadoc(state, treePos, danglingJavadoc, builder);
        builder.replace(firstModifierPos, firstModifierPos,
                String.format("%s%s ", javadoc, joinSource(state, moveBefore)))
                .replace(lastModifierPos, lastModifierPos, String.format("%s ", joinSource(state, moveAfter)));
        ImmutableList<String> names = annotations.stream().map(ASTHelpers::getSymbol).filter(Objects::nonNull)
                .map(Symbol::getSimpleName).map(a -> "@" + a).collect(toImmutableList());
        String flattened = names.stream().collect(joining(", "));
        String isAre = names.size() > 1 ? "are not type annotations" : "is not a type annotation";
        String message = String.format("%s %s, so should appear before any modifiers and after Javadocs.",
                flattened, isAre);
        return buildDescription(tree).setMessage(message).addFix(builder.build()).build();
    }
    return NO_MATCH;
}

From source file:org.ambraproject.rhino.content.xml.ArticleXml.java

private List<AssetMetadata> parseAssets() {
    AssetNodesByDoi nodeMap = findAllAssetNodes();
    return nodeMap.getDois().stream().map((Doi assetDoi) -> {
        ImmutableList<Node> nodes = nodeMap.getNodes(assetDoi);
        List<AssetMetadata> assetMetadataList = nodes.stream()
                .map(assetNode -> new AssetXml(assetNode, assetDoi).build()).distinct()
                .collect(Collectors.toList());
        if (assetMetadataList.size() > 1) {
            return disambiguateAssetNodes(assetMetadataList);
        }//from w w w. j  a v  a 2 s  .  c o m
        return assetMetadataList.get(0);
    }).collect(Collectors.toList());
}