Languages
[Edit]
EN

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

14 points
Created by:
Nicola-Melendez
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) {
            list.add(Double.valueOf(no));
        }

        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

  1. Java 8 - create stream of Double objects from primitive double array
  2. How do I convert double[] to Stream<Double> in java?
  3. Java - convert primitive double array to stream of Double objects
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join