Example usage for java.util.stream Collectors toCollection

List of usage examples for java.util.stream Collectors toCollection

Introduction

In this page you can find the example usage for java.util.stream Collectors toCollection.

Prototype

public static <T, C extends Collection<T>> Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) 

Source Link

Document

Returns a Collector that accumulates the input elements into a new Collection , in encounter order.

Usage

From source file:io.ingenieux.lambada.maven.LambadaGenerateMojo.java

@Override
protected void executeInternal() throws Exception {
    outputFile.getParentFile().mkdirs();

    final Set<Method> methodsAnnotatedWith = extractRuntimeAnnotations(LambadaFunction.class);

    // TODO: Validate clashing paths

    final TreeSet<LambadaFunctionDefinition> definitionTreeSet = methodsAnnotatedWith.stream()
            .map(f -> Unthrow.wrap(this::extractFunctionDefinitions, f))
            .collect(Collectors.toCollection(TreeSet::new));

    final List<LambadaFunctionDefinition> defList = new ArrayList<>(definitionTreeSet);

    OBJECT_MAPPER.writeValue(new FileOutputStream(outputFile), defList);
}

From source file:org.apache.solr.client.solrj.io.eval.FindDelayEvaluator.java

@Override
public Object doWork(Object first, Object second) throws IOException {
    if (null == first) {
        throw new IOException(String.format(Locale.ROOT,
                "Invalid expression %s - null found for the first value", toExpression(constructingFactory)));
    }//from ww  w  .j  a  va 2  s .  c  om
    if (null == second) {
        throw new IOException(String.format(Locale.ROOT,
                "Invalid expression %s - null found for the second value", toExpression(constructingFactory)));
    }
    if (!(first instanceof List<?>)) {
        throw new IOException(String.format(Locale.ROOT,
                "Invalid expression %s - found type %s for the first value, expecting a list of numbers",
                toExpression(constructingFactory), first.getClass().getSimpleName()));
    }
    if (!(second instanceof List<?>)) {
        throw new IOException(String.format(Locale.ROOT,
                "Invalid expression %s - found type %s for the second value, expecting a list of numbers",
                toExpression(constructingFactory), first.getClass().getSimpleName()));
    }

    // Get first and second lists as arrays, where second is in reverse order
    double[] firstArray = ((List) first).stream().mapToDouble(value -> ((BigDecimal) value).doubleValue())
            .toArray();
    double[] secondArray = StreamSupport
            .stream(Spliterators.spliteratorUnknownSize(
                    ((LinkedList) ((List) second).stream().collect(Collectors.toCollection(LinkedList::new)))
                            .descendingIterator(),
                    Spliterator.ORDERED), false)
            .mapToDouble(value -> ((BigDecimal) value).doubleValue()).toArray();

    double[] convolution = MathArrays.convolve(firstArray, secondArray);
    double maxValue = -Double.MAX_VALUE;
    double indexOfMaxValue = -1;

    for (int idx = 0; idx < convolution.length; ++idx) {
        double abs = Math.abs(convolution[idx]);
        if (abs > maxValue) {
            maxValue = abs;
            indexOfMaxValue = idx;
        }
    }

    return (indexOfMaxValue + 1) - secondArray.length;

}

From source file:Imputers.KnniLDProbOptimizedCalls.java

public KnniLDProb getOptimized(double[][][] callprobs, int[][][] readCounts,
        List<SingleGenotypeProbability> maskedprobs, List<SingleGenotypeMasked> list) {
    ProbToCallMinDepth p2c = new ProbToCallMinDepth(knownDepth);

    byte[][] original = p2c.call(callprobs, readCounts);

    Correlation corr = new Pearson();

    Set<Integer> ldcalc = list.stream().map(SingleGenotypePosition::getSNP)
            .collect(Collectors.toCollection(HashSet::new));

    byte[][] transposed = Matrix.transpose(original);

    Map<Integer, int[]> ld;
    if (ldcalc.size() < (transposed.length / 2)) {
        ld = corr.limitedtopn(transposed, 100, ldcalc);
    } else {//  w w  w .j a v  a2s  .co m
        ld = corr.topn(transposed, 100);
    }

    List<SingleGenotypeCall> correct = list.stream().map(sgp -> new SingleGenotypeCall(sgp.getSample(),
            sgp.getSNP(), original[sgp.getSample()][sgp.getSNP()]))
            .collect(Collectors.toCollection(ArrayList::new));

    int[][] sim = new int[original[0].length][];
    for (Map.Entry<Integer, int[]> e : ld.entrySet()) {
        sim[e.getKey()] = e.getValue();
    }

    Opt opt = new Opt(original, sim, maskedprobs, list, correct, method);

    int[] min = { 1, 1 };
    int[] max = { original.length, 100 };
    int[] init = { 5, 20 };
    Descent descent = new Descent();
    int[] best = descent.optimize(opt, init, min, max);

    int k = best[0];
    int l = best[1];

    return new KnniLDProb(k, l, knownDepth);
}

From source file:com.wormsim.simulation.Walker.java

/**
 * Creates a new walker using the specified class of random number generator
 * and the provided seed. Note there is a requirement that the provided random
 * number generator is {@link java.io.Serializable}.
 *
 * @param cls                The random number generator class
 * @param seed               The seed// w  w w.  j  a  va  2s.c o  m
 * @param zoo                The animal zoo to use
 * @param fitness            The fitness tracker
 * @param tracked_quantities Quantities tracked in the simulation.
 *
 * @throws IllegalArgumentException If the provided generator does not have a
 *                                  empty argument constructor or the
 *                                  constructor is illegal to access.
 */
public Walker(Class<? extends RandomGenerator> cls, long seed, AnimalZoo2 zoo, TrackedCalculation fitness,
        ArrayList<TrackedCalculation> tracked_quantities) throws IllegalArgumentException {
    try {
        if (!Serializable.class.isAssignableFrom(cls)) {
            throw new IllegalArgumentException("The provided class must be serializable.");
        }
        this.rng = cls.newInstance();
        this.seed = seed;
        this.rng.setSeed(seed);
        this.zoo = zoo.generate(rng);
        this.fitness = fitness.generate(rng);
        this.tracked_quantities = tracked_quantities.stream().map((v) -> v.generate(rng))
                .collect(Collectors.toCollection(ArrayList::new));
        this.tracked_quantities.add(this.fitness);
    } catch (InstantiationException | IllegalAccessException ex) {
        Logger.getLogger(Walker.class.getName()).log(Level.SEVERE, null, ex);
        throw new IllegalArgumentException(ex);
    }
}

From source file:Combiner.MaxDepthCombiner.java

public List<SingleGenotypeProbability> combine(List<SingleGenotypeProbability> called,
        List<SingleGenotypeProbability> imputed, List<SingleGenotypeReads> reads) {
    if (!SingleGenotypePosition.samePositions(called, imputed)) {
        //Throw Exception
    }/* ww w .j  av  a 2 s  .  c  om*/

    Progress progress = ProgressFactory.get(called.size());
    return IntStream.range(0, called.size()).parallel().mapToObj(i -> {
        SingleGenotypeProbability c = called.get(i);
        SingleGenotypeProbability sgp = new SingleGenotypeProbability(c.getSample(), c.getSNP(),
                combineSingle(c.getProb(), imputed.get(i).getProb(), reads.get(i).getReads()));
        progress.done();
        return sgp;
    }).collect(Collectors.toCollection(ArrayList::new));
}

From source file:com.netflix.spinnaker.halyard.core.registry.v1.GitProfileReader.java

@Override
public InputStream readArchiveProfile(String artifactName, String version, String profileName)
        throws IOException {
    Path profilePath = Paths.get(profilePath(artifactName, version, profileName));

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    TarArchiveOutputStream tarArchive = new TarArchiveOutputStream(os);

    ArrayList<Path> filePathsToAdd = java.nio.file.Files
            .walk(profilePath, Integer.MAX_VALUE, FileVisitOption.FOLLOW_LINKS)
            .filter(path -> path.toFile().isFile()).collect(Collectors.toCollection(ArrayList::new));

    for (Path path : filePathsToAdd) {
        TarArchiveEntry tarEntry = new TarArchiveEntry(path.toFile(), profilePath.relativize(path).toString());
        int permissions = FileModeUtils.getFileMode(Files.getPosixFilePermissions(path));
        permissions = FileModeUtils.setFileBit(permissions);
        tarEntry.setMode(permissions);//from  w w w  .ja  va 2  s .  c  o  m
        tarArchive.putArchiveEntry(tarEntry);
        IOUtils.copy(Files.newInputStream(path), tarArchive);
        tarArchive.closeArchiveEntry();
    }

    tarArchive.finish();
    tarArchive.close();

    return new ByteArrayInputStream(os.toByteArray());
}

From source file:starnubserver.plugins.PluginManager.java

public HashSet<String> getAllUnloadedPluginNames() {
    return UNLOADED_PLUGINS.keySet().stream().collect(Collectors.toCollection(HashSet::new));
}

From source file:org.lightjason.agentspeak.action.builtin.rest.IBaseRest.java

/**
 * creates a literal structure from a stream of string elements,
 * the string stream will be build in a tree structure
 *
 * @param p_functor stream with functor strings
 * @param p_values value stream//w  w w.  j  a va2 s  .  co  m
 * @return term
 */
@Nonnull
protected static ITerm baseliteral(@Nonnull final Stream<String> p_functor,
        @Nonnull final Stream<ITerm> p_values) {
    final Stack<String> l_tree = p_functor.collect(Collectors.toCollection(Stack::new));

    ILiteral l_literal = CLiteral.from(l_tree.pop(), p_values);
    while (!l_tree.isEmpty())
        l_literal = CLiteral.from(l_tree.pop(), l_literal);

    return l_literal;
}

From source file:com.github.robozonky.app.version.UpdateMonitor.java

static VersionIdentifier parseNodeList(final NodeList nodeList) {
    final SortedSet<String> versions = IntStream.range(0, nodeList.getLength()).mapToObj(nodeList::item)
            .map(Node::getTextContent)
            .collect(Collectors.toCollection(() -> new TreeSet<>(new VersionComparator().reversed())));
    // find latest stable
    final String firstStable = UpdateMonitor.findFirstStable(versions);
    // and check if it is followed by any other unstable versions
    final String first = versions.first();
    if (Objects.equals(first, firstStable)) {
        return new VersionIdentifier(firstStable);
    } else {/* w  w  w . ja v  a2s  . c o m*/
        return new VersionIdentifier(firstStable, first);
    }
}

From source file:starnubserver.plugins.PluginManager.java

public HashSet<UnloadedPlugin> getAllUnloadedPlugins() {
    return UNLOADED_PLUGINS.values().stream().collect(Collectors.toCollection(HashSet::new));
}