Example usage for java.util.stream IntStream of

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

Introduction

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

Prototype

public static IntStream of(int... values) 

Source Link

Document

Returns a sequential ordered stream whose elements are the specified values.

Usage

From source file:Main.java

public static void main(String[] args) {
    IntStream i = IntStream.of(1);
    i.forEach(System.out::println);
}

From source file:Main.java

public static void main(String[] args) {
    List<String> stringList = Arrays.asList("1.2", "2.2", "3", "4", "5");

    stringList.stream().flatMapToInt(n -> IntStream.of(Integer.parseInt(n))).forEach(System.out::println);
}

From source file:ipnat.skel.SummarizeSkeleton.java

@Override
public void run(final ImageProcessor ignored) {

    // Analyze skeleton
    final AnalyzeSkeleton_ as = new AnalyzeSkeleton_();
    as.setup("", imp);
    final SkeletonResult sr = as.run();

    // Get key skeleton properties
    final int nTrees = sr.getNumOfTrees();
    final int[] branches = sr.getBranches();
    final int nBranches = IntStream.of(branches).sum();

    if (branches == null || (nBranches == 0 && nTrees <= 1)) {
        Utils.error("Summarize Skeleton", "Image does not seem to be a branched skeleton.", imp);
        return;/*from   w w  w  . j  a v a2  s.  c  o m*/
    }

    final ResultsTable rt = Utils.getTable(TABLE_TITLE);
    try {

        // Integrate values from all trees
        double sumLength = 0d;
        final double[] avgLengths = sr.getAverageBranchLength();
        for (int i = 0; i < nTrees; i++)
            sumLength += avgLengths[i] * branches[i];

        // Log stats
        rt.incrementCounter();
        rt.addValue("Image", imp.getTitle());
        rt.addValue("Unit", imp.getCalibration().getUnits());
        rt.addValue("Total length", sumLength);
        rt.addValue("Max branch length", StatUtils.max(sr.getMaximumBranchLength()));
        rt.addValue("Mean branch length", StatUtils.mean(avgLengths));
        rt.addValue("# Trees", nTrees);
        rt.addValue("# Branches", nBranches);
        rt.addValue("# Junctions", IntStream.of(sr.getJunctions()).sum());
        rt.addValue("# End-points", IntStream.of(sr.getEndPoints()).sum());
        rt.addValue("# Triple Points", IntStream.of(sr.getTriples()).sum());
        rt.addValue("# Quadruple Points", IntStream.of(sr.getQuadruples()).sum());
        rt.addValue("Sum of voxels", IntStream.of(sr.calculateNumberOfVoxels()).sum());

    } catch (final Exception ignored1) {

        Utils.error("Summarize Skeleton", "Some statistics could not be calculated", imp);

    } finally {

        rt.show(TABLE_TITLE);

    }

}

From source file:io.pivotal.demo.smartgrid.frontend.timeseries.AggregateCounterTimeSeriesRepository.java

@Override
public Map<String, TimeSeriesCollection> getTimeSeriesData(TimeSeriesDataRequest dataRequest) {

    int houseId = dataRequest.getHouseId();

    IntStream houseNumStream = houseId == GRID_HOUSE_ID ? IntStream.rangeClosed(HOUSE_ID_MIN, HOUSE_ID_MAX)
            : IntStream.of(houseId);

    List<AggregateCounterCollection> aggregateCounterCollections = houseNumStream.parallel()
            .mapToObj(i -> new TimeSeriesDataRequest(dataRequest, i)).map(this::fetchAggregateCounterData)
            .filter(acc -> acc != null && !acc.getAggregateCounters().isEmpty()).collect(Collectors.toList());

    Map<String, TimeSeriesCollection> result = new HashMap<>();
    for (AggregateCounterCollection acc : aggregateCounterCollections) {

        TimeSeriesCollection tsc = convertToTimeSeriesCollection(acc);
        result.put(tsc.getName(), tsc);//from w w  w.j av  a  2  s.  co m
    }

    TimeSeriesCollection totalGridTimeSeriesCollection = aggreagteGridTotalTimeSeries(result);

    result.put("h_-1", totalGridTimeSeriesCollection);

    return result;
}

From source file:com.amazon.janusgraph.ScenarioTests.java

/**
 * This test is to demonstrate performance in response to a report of elevated latency for committing 30 vertices.
 * http://stackoverflow.com/questions/42899388/titan-dynamodb-local-incredibly-slow-8s-commit-for-30-vertices
 * @throws BackendException/*from   w w w .j a va2 s.c o m*/
 */
@Test
public void performanceTest() throws BackendException {
    final Graph graph = JanusGraphFactory
            .open(TestGraphUtil.instance.createTestGraphConfig(BackendDataModel.MULTI));
    IntStream.of(30).forEach(i -> graph.addVertex(LABEL));
    Stopwatch watch = Stopwatch.createStarted();
    graph.tx().commit();
    System.out.println("Committing took " + watch.stop().elapsed(TimeUnit.MILLISECONDS) + " ms");
    TestGraphUtil.instance.cleanUpTables();
}

From source file:org.diorite.firework.FireworkEffect.java

/**
 * Deserialize FireworkEffect from {@link NbtTagCompound}.
 *
 * @param tag data to deserialize./*  ww w . java 2  s .c  om*/
 */
public FireworkEffect(final NbtTagCompound tag) {
    this.flicker = tag.getBoolean("Flicker");
    this.trail = tag.getBoolean("Trail");
    this.colors = ImmutableList.copyOf(
            IntStream.of(tag.getIntArray("Colors")).mapToObj(Color::fromRGB).collect(Collectors.toList()));
    this.fadeColors = tag.containsTag("FadeColors") ? ImmutableList.copyOf(
            IntStream.of(tag.getIntArray("FadeColors")).mapToObj(Color::fromRGB).collect(Collectors.toList()))
            : ImmutableList.of();
    this.type = FireworkEffectType.getByTypeID(tag.getByte("Type"));
}

From source file:onl.area51.metoffice.metoffice.forecast.layer.ForecastImageLayerWS.java

protected HttpEntity sendLayer(String layerName, Request request) {
    Layer layer = forecastImageLayerService.getLayer(request.getAttribute(layerName));
    if (layer != null) {
        return new JsonEntity(Json.createObjectBuilder().add("name", layer.getName())
                .add("layerName", layer.getLayerName()).add("displayName", layer.getDisplayName())
                .add("defaultTime", layer.getDefaultTime()).add("format", layer.getFormat())
                // Array of timesteps
                .add("timestep", IntStream.of(layer.getTimestep()).mapToObj(Integer::valueOf).reduce(
                        Json.createArrayBuilder(), (a, i) -> a.add(i), Functions.writeOnceBinaryOperator()))
                // Map of timestep to actual image url
                .add("images", IntStream.of(layer.getTimestep()).mapToObj(Integer::valueOf)
                        .reduce(Json.createObjectBuilder(), (a, ts) -> {
                            Path p = forecastImageLayerService.getPath(layer, ts);
                            if (p != null) {
                                String ps = p.toString();
                                if (!ps.startsWith("/")) {
                                    ps = "/" + ps;
                                }/*  w  ww  .  j  ava  2s.c o m*/
                                a.add(String.valueOf(ts), PREFIX + ps);
                            }
                            return a;
                        }, Functions.writeOnceBinaryOperator())));
    }
    return null;
}

From source file:com.asakusafw.runtime.io.csv.CsvEmitter.java

private BitSet buildQuoteMask(int[] indices) {
    if (indices.length == 0) {
        return null;
    }/*www  .ja v a  2s.  co m*/
    BitSet results = new BitSet();
    IntStream.of(indices).forEach(results::set);
    return results;
}

From source file:tracing.SkeletonPlugin.java

private void summarizeSkeleton(final SkeletonResult sr) {
    final String TABLE_TITLE = "Summary of Rendered Paths";
    final ResultsTable rt = getTable(TABLE_TITLE);
    try {/* w  ww  .java 2 s.c  om*/
        double sumLength = 0d;
        final int[] branches = sr.getBranches();
        final double[] avgLengths = sr.getAverageBranchLength();
        for (int i = 0; i < sr.getNumOfTrees(); i++)
            sumLength += avgLengths[i] * branches[i];
        rt.incrementCounter();
        rt.addValue("N. Rendered Paths", renderingPaths.size());
        rt.addValue("Unit", imp.getCalibration().getUnits());
        rt.addValue("Total length", sumLength);
        rt.addValue("Mean branch length", StatUtils.mean(avgLengths));
        rt.addValue("Length of longest branch", StatUtils.max(sr.getMaximumBranchLength()));
        rt.addValue("# Branches", IntStream.of(sr.getBranches()).sum());
        rt.addValue("# Junctions", IntStream.of(sr.getJunctions()).sum());
        rt.addValue("# End-points", IntStream.of(sr.getEndPoints()).sum());
        rt.addValue("Fitering", getFilterString());
        if (restrictByRoi && roi != null && roi.isArea())
            rt.addValue("ROI Name", roi.getName() == null ? "Unammed ROI" : roi.getName());

    } catch (final Exception ignored) {
        SNT.error("Some statistics could not be calculated.");
    } finally {
        rt.show(TABLE_TITLE);
    }
}

From source file:org.chemid.structure.dbclient.chemspider.ChemSpiderClient.java

/**
 * Query the ChemSpider Database by Mass and Error values.
 *
 * @param mass     : Experimental mass value.
 * @param error    : Instrumentation error.
 * @param location : location where file to be save
 * @return The string containing the list of CSID values of resultant molecules.
 * @throws ChemIDStructureException/*www  .  jav  a 2s .com*/
 */
public String getChemicalStructuresByMass(Double mass, Double error, String location)
        throws ChemIDStructureException {
    String sdfPath = null;
    String timeOut = HTTPConstants.CONNECTION_TIMEOUT;

    try {
        MassSpecAPIStub massSpecAPIStub = new MassSpecAPIStub();
        massSpecAPIStub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
        massSpecAPIStub._getServiceClient().getOptions().setProperty(timeOut, connectionTimeout);
        massSpecAPIStub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, soTimeOut);
        massSpecAPIStub._getServiceClient().getOptions().setCallTransportCleanup(true);
        MassSpecAPIStub.SearchByMassAsync searchByMassAsync = new MassSpecAPIStub.SearchByMassAsync();
        searchByMassAsync.setMass(mass);
        searchByMassAsync.setRange(error);
        searchByMassAsync.setToken(this.token);

        MassSpecAPIStub.SearchByMassAsyncResponse massAsyncResponse = massSpecAPIStub
                .searchByMassAsync(searchByMassAsync);

        SearchStub thisSearchStub = new SearchStub();
        thisSearchStub._getServiceClient().getOptions().setProperty(HTTPConstants.CHUNKED, false);
        thisSearchStub._getServiceClient().getOptions().setProperty(timeOut, connectionTimeout);
        thisSearchStub._getServiceClient().getOptions().setProperty(HTTPConstants.SO_TIMEOUT, soTimeOut);
        SearchStub.GetAsyncSearchResult getAsyncSearchResultInput = new SearchStub.GetAsyncSearchResult();
        getAsyncSearchResultInput.setRid(massAsyncResponse.getSearchByMassAsyncResult());
        getAsyncSearchResultInput.setToken(token);

        SearchStub.GetAsyncSearchResultResponse thisGetAsyncSearchResultResponse = thisSearchStub
                .getAsyncSearchResult(getAsyncSearchResultInput);

        //list of CIDs
        int[] output = thisGetAsyncSearchResultResponse.getGetAsyncSearchResultResult().get_int();

        if (output.length > 0) {
            sdfPath = getChemicalStructuresByCsids(IntStream.of(output).distinct().toArray(), location);
            thisSearchStub.cleanup();
            massSpecAPIStub._getServiceClient().cleanupTransport();
            massSpecAPIStub.cleanup();
        }

        return sdfPath;
    } catch (RemoteException e) {
        throw new ChemIDStructureException("Error occurred while downloading chemspider results: ", e);
    }
}