posted on: 2015-05-24 13:22:02
A collection of stream examples that I will build up, and improve, over time.

So this first one is to take a comma separated string and get a list of integers.

String s = "1,2,3,4,5";
List<Integer> ints = Arrays.stream(
        s.split(",")
    ).map(
        Integer::new
    ).collect(
        Collectors.toList()
    );

Read a file and split all of the lines of tab separated values.

List<double[]> values = Files.lines(
                f.toPath(), Charset.forName("UTF-8")
        ).filter((l)->!l.startsWith("#")).map(
                (l) -> Arrays.stream(
                        l.split("\\t")
                ).mapToDouble(Double::parseDouble).toArray()
        ).filter((v)->v.length>0).collect(Collectors.toCollection(ArrayList::new));

Create a set of double[]s for a range of values.


List<double[]> op = IntStream.range(0, bins).mapToObj(
                (i)->new double[]{(i+0.5)*delta + min, 0}
            ).collect(Collectors.toCollection(ArrayList::new));

Broken example of steam usage because the stream is lazy. In this example amax and amin will not get set until the stream is consumed. This is broken then because, I want to use the values when I consume the stream!


    final AtomicDouble amax = new AtomicDouble(-Double.MAX_VALUE);
    final AtomicDouble amin = new AtomicDouble(Double.MAX_VALUE);

    DoubleStream sv = values.stream().mapToDouble(
        (v) ->{
            double r = v[index];
            amax.setIfGreater(r);
            amin.setIfLess(r);
            return r;
        }
    );

To improve this the we should switch to using two streams with a forEach.


    final AtomicDouble amax = new AtomicDouble(-Double.MAX_VALUE);
    final AtomicDouble amin = new AtomicDouble(Double.MAX_VALUE);

    values.forEach(
            (v) ->{

                double r = v[index];
                amax.setIfGreater(r);
                amin.setIfLess(r);

            });

    DoubleStream sv = values.stream().mapToDouble(
        (v) ->{
            double r = v[index];
            return r;
    });


Or even better, just use a summary statistics class.

    DoubleSummaryStatistics stats = Arrays.stream(values).summaryStatistics()
    double min = stats.getMin();
    double max = stats.getMax();

Comments

Name: