Example usage for java.util.stream StreamSupport stream

List of usage examples for java.util.stream StreamSupport stream

Introduction

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

Prototype

public static <T> Stream<T> stream(Spliterator<T> spliterator, boolean parallel) 

Source Link

Document

Creates a new sequential or parallel Stream from a Spliterator .

Usage

From source file:com.act.lcms.v2.MassChargeCalculatorTest.java

@Test
public void testMakeMassChargeMap() throws Exception {
    List<MassChargeCalculator.MZSource> sources = Arrays.asList(
            new MassChargeCalculator.MZSource("InChI=1S/C7H7NO2/c8-6-3-1-5(2-4-6)7(9)10/h1-4H,8H2,(H,9,10)"), // PABA
            new MassChargeCalculator.MZSource("InChI=1S/C7H7NO2/c1-10-7(9)6-3-2-4-8-5-6/h2-5H,1H3")); // Something crazy.

    MassChargeCalculator.MassChargeMap massChargeMap = MassChargeCalculator.makeMassChargeMap(sources,
            new HashSet<>(Arrays.asList("M+H", "M+Na")));

    Double expectedMonoMass = 137.047679;
    List<Double> expectedIonMZs = Arrays.asList(138.054979, 160.036879); // M+H and M+Na of PABA

    // This is package private, but we'll use its ordering to speed testing.
    List<Double> actualIonMasses = massChargeMap.ionMZsSorted();
    assertEqualsWithFPErr("Unique ionic masses match expected list", expectedIonMZs, actualIonMasses);

    assertEqualsPairWithFPErr("M+H ion mz maps to source mass and ion name",
            Arrays.asList(Pair.of("M+H", expectedMonoMass)),
            massChargeMap.ionMZtoMonoMassAndIonName(actualIonMasses.get(0)));

    assertEqualsPairWithFPErr("M+Na ion mz maps to source mass and ion name",
            Arrays.asList(Pair.of("M+Na", expectedMonoMass)),
            massChargeMap.ionMZtoMonoMassAndIonName(actualIonMasses.get(1)));

    // Test reverse mapping.
    for (Double ionMZ : actualIonMasses) {
        assertEquals(String.format("Ionic masses for %f map to two MZSources", ionMZ), new HashSet<>(sources),
                massChargeMap.ionMZToMZSources(ionMZ));
    }/*w  w w.  j  a  v a 2s  . c  o  m*/

    // Test iterators cover all values.
    assertEqualsWithFPErr("Iterable ionMZs match expected", new HashSet<>(expectedIonMZs),
            StreamSupport.stream(massChargeMap.ionMZIter().spliterator(), false).collect(Collectors.toSet()));

    assertEqualsWithFPErr("Iterable monoisotopic masses match expected",
            Collections.singleton(expectedMonoMass),
            StreamSupport.stream(massChargeMap.monoisotopicMassIter().spliterator(), false)
                    .collect(Collectors.toSet()));

    assertEquals("Iterable mzSources match expected", new HashSet<>(sources), StreamSupport
            .stream(massChargeMap.mzSourceIter().spliterator(), false).collect(Collectors.toSet()));
}

From source file:com.simiacryptus.mindseye.test.data.MNIST.java

private static <T> Stream<T> toStream(@Nonnull final Iterator<T> iterator, final int size,
        final boolean parallel) {
    return StreamSupport.stream(Spliterators.spliterator(iterator, size, Spliterator.ORDERED), parallel);
}

From source file:nl.knaw.huygens.alexandria.service.TitanService.java

private List<IndexInfo> indexInfo(TitanManagement mgmt, Class<? extends Element> elementClass) {
    return StreamSupport.stream(mgmt.getGraphIndexes(elementClass).spliterator(), false)//
            .map(IndexInfo::new)//
            .collect(toList());/*www .j  a va 2  s. c  o m*/
}

From source file:com.spankingrpgs.util.LoadStateUtils.java

/**
 * Given a Loader, and a path to data files, loads the data from the files into the game using the loader.
 *
 * @param loader  The loader to use to load data into the game
 * @param dataPath  The path containing the files containing the data to load
 * @param fileGlob  A glob that describes the kinds of files to load
 * @param newLineMarker  The String to use to represent new lines
 *//*  ww w  .  jav a2 s. c  o  m*/
public static void loadData(Loader loader, Path dataPath, String fileGlob, String newLineMarker) {
    LOG.info(String.format("Loading %s", dataPath));
    try {
        PathMatcher jsonMatcher = FileSystems.getDefault().getPathMatcher(fileGlob);
        Collection<String> data = StreamSupport.stream(Files.newDirectoryStream(dataPath).spliterator(), false)
                .peek(path -> LOG.fine(String.format("Loading data from %s", path)))
                .filter(jsonMatcher::matches).map((Path path) -> {
                    try {
                        return String.join(newLineMarker, Files.readAllLines(path));
                    } catch (IOException e) {
                        String msg = String.format("Problem reading file: %s", path);
                        LOG.log(Level.SEVERE, String.format("%s with exception:%s", msg, e), e);
                        throw new RuntimeException(msg);
                    }
                }).collect(Collectors.toList());
        loader.load(data, GameState.getCleanInstance());
    } catch (IOException exception) {
        String msg = String.format("Problem reading files in: %s", dataPath);
        LOG.log(Level.SEVERE, String.format("%s with exception: %s", msg, exception), exception);
        throw new RuntimeException(msg);
    }
}

From source file:org.xwiki.contrib.repository.npm.internal.NpmExtensionRepository.java

protected Optional<Version> getNewestCompatibleVersion(VersionConstraint versionConstraint,
        IterableResult<Version> versions) {
    return StreamSupport.stream(versions.spliterator(), false).sorted((v1, v2) -> {
        return new NpmVersion(v1).isNewer(new NpmVersion(v2));
    }).filter(version -> versionConstraint.isCompatible(version)).findFirst();
}

From source file:com.wrmsr.kleist.util.Itertools.java

public static <T> Stream<T> lazyStream(Supplier<? extends T> supplier) {
    return StreamSupport.stream(Spliterators.spliterator(lazyIterator(supplier), 1, Spliterator.SIZED), false);
}

From source file:com.yevster.spdxtra.Read.java

public static Stream<SpdxPackage> getAllPackages(Dataset dataset) {

    try (DatasetAutoAbortTransaction transaction = DatasetAutoAbortTransaction.begin(dataset, ReadWrite.READ)) {

        String sparql = createSparqlQueryByType(SpdxUris.SPDX_PACKAGE);
        QueryExecution qe = QueryExecutionFactory.create(sparql, dataset);
        ResultSet results = qe.execSelect();
        Stream<QuerySolution> querySolutionStream = StreamSupport.stream(
                Spliterators.spliteratorUnknownSize(results, Spliterator.ORDERED | Spliterator.NONNULL), false);

        return querySolutionStream.map((QuerySolution qs) -> {
            RDFNode subject = qs.get("s");
            return new SpdxPackage(subject.asResource());
        });/*www.  j  a  v  a  2  s .  c  o m*/
    }
}

From source file:no.ssb.jsonstat.v2.DatasetTest.java

@Test
public void testGetRows() throws Exception {

    Dataset dataset = Dataset.create("test")
            .withDimensions(Dimension.create("A").withCategories("A1", "A2", "A3"),
                    Dimension.create("B").withCategories("B1", "B2"),
                    Dimension.create("C").withCategories("C1", "C2", "C3", "C4"))
            .withMapper(strings -> String.join("", strings).hashCode()).build();

    List<Object> result = StreamSupport.stream(dataset.getRows().spliterator(), false)
            .collect(Collectors.toList());

    List<Integer> expected = Lists.transform(
            newArrayList("A1B1C1", "A1B1C2", "A1B1C3", "A1B1C4", "A1B2C1", "A1B2C2", "A1B2C3", "A1B2C4",

                    "A2B1C1", "A2B1C2", "A2B1C3", "A2B1C4", "A2B2C1", "A2B2C2", "A2B2C3", "A2B2C4",

                    "A3B1C1", "A3B1C2", "A3B1C3", "A3B1C4", "A3B2C1", "A3B2C2", "A3B2C3", "A3B2C4"),
            String::hashCode);/*from   ww w.  jav  a2  s  . c om*/

    assertThat(result).containsExactlyElementsOf(expected);

}

From source file:com.github.steveash.guavate.Guavate.java

/**
 * Creates a stream that combines two other streams, continuing until either stream ends.
 * <p>/* w w  w.java 2 s  . c om*/
 * The combiner function is called once for each pair of objects found in the input streams.
 * @param <A> the type of the first stream
 * @param <B> the type of the second stream
 * @param <R> the type of the resulting stream
 * @param stream1 the first stream
 * @param stream2 the first stream
 * @param zipper the function used to combine the pair of objects
 * @return a stream of pairs, one from each stream
 */
private static <A, B, R> Stream<R> zip(Stream<A> stream1, Stream<B> stream2, BiFunction<A, B, R> zipper) {
    // this is private for now, to see if it is really needed on the API
    // it suffers from generics problems at the call site with common zipper functions
    // as such, it is less useful than it might seem
    Spliterator<A> split1 = stream1.spliterator();
    Spliterator<B> split2 = stream2.spliterator();
    // merged stream lacks some characteristics
    int characteristics = split1.characteristics() & split2.characteristics()
            & ~(Spliterator.DISTINCT | Spliterator.SORTED);
    long size = Math.min(split1.getExactSizeIfKnown(), split2.getExactSizeIfKnown());

    Iterator<A> it1 = Spliterators.iterator(split1);
    Iterator<B> it2 = Spliterators.iterator(split2);
    Iterator<R> it = new Iterator<R>() {
        @Override
        public boolean hasNext() {
            return it1.hasNext() && it2.hasNext();
        }

        @Override
        public R next() {
            return zipper.apply(it1.next(), it2.next());
        }
    };
    Spliterator<R> split = Spliterators.spliterator(it, size, characteristics);
    return StreamSupport.stream(split, false);
}

From source file:org.apache.tinkerpop.gremlin.process.traversal.Traversal.java

/**
 * Return the traversal as a {@link Stream}.
 *
 * @return the traversal as a stream.//from   w w w  .j a v  a 2s. c o  m
 */
public default Stream<E> toStream() {
    return StreamSupport.stream(
            Spliterators.spliteratorUnknownSize(this, Spliterator.IMMUTABLE | Spliterator.SIZED), false);
}