Close

Java 8 Streams - StreamSupport.doubleStream() Examples

Java 8 Streams Java Java API 


Class:

java.util.stream.StreamSupport

java.lang.Objectjava.lang.Objectjava.util.stream.StreamSupportjava.util.stream.StreamSupportLogicBig

Methods:

public static DoubleStream doubleStream(Spliterator.OfDouble spliterator,
                                        boolean parallel)

Creates a new sequential or parallel DoubleStream from a Spliterator.OfDouble.



public static DoubleStream doubleStream(Supplier<? extends Spliterator.OfDouble> supplier,
                                        int characteristics,
                                        boolean parallel)

Creates a new sequential or parallel DoubleStream from a Supplier of Spliterator.OfDouble . This method also specifies the characteristics of the supplied Spliterator.

See also Iterator vs Spliterator.


Examples


package com.logicbig.example.streamsupport;

import java.util.Arrays;
import java.util.stream.DoubleStream;
import java.util.stream.StreamSupport;

public class DoubleStreamExample {

public static void main(String... args) {
DoubleStream ds = StreamSupport
.doubleStream(Arrays.spliterator(new double[]{1, 3, 6}), false);
double sum = ds.sum();
System.out.println(sum);
}
}

Output

10.0




package com.logicbig.example.streamsupport;

import java.util.Arrays;
import java.util.Spliterator;
import java.util.stream.DoubleStream;
import java.util.stream.StreamSupport;

public class DoubleStreamExample2 {

public static void main(String... args) {
DoubleStream ds = StreamSupport
.doubleStream(() -> Arrays.spliterator(new double[]{3, 1, 6}), Spliterator.DISTINCT, false);
ds.forEach(System.out::println);
}
}

Output

3.0
1.0
6.0




Using a custom Spliterator.OfDouble:

package com.logicbig.example.streamsupport;

import java.util.Spliterator;
import java.util.Spliterators;
import java.util.SplittableRandom;
import java.util.function.DoubleConsumer;
import java.util.stream.DoubleStream;
import java.util.stream.StreamSupport;

public class DoubleStreamExample3 {

public static void main(String... args) {
DoubleStream ds = StreamSupport
.doubleStream(createSpliterator(3), false);
ds.forEach(System.out::println);
}

private static Spliterator.OfDouble createSpliterator(int est) {

return new Spliterators.AbstractDoubleSpliterator(3, 0) {
double first = new SplittableRandom().nextDouble();
int c = 0;

@Override
public boolean tryAdvance(DoubleConsumer action) {
if (c++ == 3) {
return false;
}
action.accept(first + c);
return true;
}
};
}
}

Output

1.6408184134945287
2.6408184134945287
3.6408184134945287




See Also