Home Communities
IT Knowledge
Inspiration
Languages
EN

# Java 8 - convert double[] to Stream<Double>

14 points
Created by:
375

Short solutions:

``````double[] array = {1.0, 2.0, 3.0, 4.0};

// solution 1
Stream<Double> stream = DoubleStream.of(array).boxed();

List<Double> list = stream.collect(Collectors.toList());

// solution 2
Stream<Double> stream2 = Arrays.stream(array).boxed();

List<Double> list2 = stream2.collect(Collectors.toList());``````

In this post, we're going to see how to create stream of Double from primitive double[] array.

## 1. Using DoubleStream.of()

``````import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.Stream;

public class Example1 {

public static void main(String[] args) {

double[] array = {1.0, 2.0, 3.0, 4.0};

Stream<Double> doubleStream = DoubleStream.of(array).boxed();

List<Double> list = doubleStream.collect(Collectors.toList());
System.out.println(list); // [1.0, 2.0, 3.0, 4.0]
}
}``````

Output:

``[1.0, 2.0, 3.0, 4.0]``

## 2. Using Arrays.stream()

``````import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example2 {

public static void main(String[] args) {

double[] array = {1.0, 2.0, 3.0, 4.0};

Stream<Double> doubleStream = Arrays.stream(array).boxed();

List<Double> list = doubleStream.collect(Collectors.toList());
System.out.println(list); // [1.0, 2.0, 3.0, 4.0]
}
}``````

Output:

``[1.0, 2.0, 3.0, 4.0]``

## 3. Explicit iteration over array

It is definitely overkill, because we create list to call stream on created list.

``````import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Example3 {

public static void main(String[] args) {

double[] array = {1.0, 2.0, 3.0, 4.0};

List<Double> list = new ArrayList<>();
for (double no : array) {
}

Stream<Double> doubleStream = list.stream();

List<Double> collect = doubleStream.collect(Collectors.toList());
System.out.println(collect); // [1.0, 2.0, 3.0, 4.0]
}
}``````

Output:

``[1.0, 2.0, 3.0, 4.0]``

## Merged questions

Join to our subscribers to be up to date with content, news and offers.