Languages
[Edit]
EN

Java - convert double[] to List<Double> - primitive double array to list of objects

7 points
Created by:
Romana-Little
368

Problem description

// We have:
double[] arr = {1.2, 2.7, 3.9};
// And we want to convert this array to list:
List<Double> list; // [1.2, 2.7, 3.9]

1. Best solution - DoubleStream.of (Java 8)

double[] arr = {1.2, 2.7, 3.9};
List<Double> list = DoubleStream.of(arr).boxed().collect(Collectors.toList());
System.out.println(list); // [1.2, 2.7, 3.9]

Output:

[1.2, 2.7, 3.9]

2. DoubleStream.of + return ArrayList (Java 8)

Return required implementation eg ArrayList or HashSet

double[] arr = {1.2, 2.7, 3.9};
ArrayList<Double> list = DoubleStream.of(arr).boxed()
		.collect(Collectors.toCollection(ArrayList::new));
System.out.println(list); // [1.2, 2.7, 3.9]

Output:

[1.2, 2.7, 3.9]

3. Explicit iteration over array (before Java 8)

double[] arr = {1.2, 2.7, 3.9};
List<Double> list = new ArrayList<>();
for (double no : arr) {
    list.add(Double.valueOf(no));
    // we can also just add primitive double
}
System.out.println(list); // [1.2, 2.7, 3.9]

Output:

[1.2, 2.7, 3.9]

4. Doubles.asList (Guava)

double[] arr = {1.2, 2.7, 3.9};
List<Double> list = Doubles.asList(arr);
System.out.println(list); // [1.2, 2.7, 3.9]

Output:

[1.2, 2.7, 3.9]

5. ArrayUtils.toObject (Apache commons lang3)

double[] arr = {1.2, 2.7, 3.9};
Double[] doubleArray = ArrayUtils.toObject(arr);
List<Double> list = Arrays.asList(doubleArray);
System.out.println(list); // [1.2, 2.7, 3.9]

Output:

[1.2, 2.7, 3.9]

Summary - in java we can convert double[] to List<Double> by:

  1. Best solution - DoubleStream.of (Java 8)
  2. DoubleStream.of + return ArrayList (Java 8)
  3. Explicit iteration over array (before Java 8)
  4. Doubles.asList (Guava)
  5. ArrayUtils.toObject (Apache commons lang3)

Reference

  1. DoubleStream.of - Java 8 docs
  2. Doubles.asList - Guava docs
  3. ArrayUtils.toObject - Apache commons lang3 docs
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.

Java conversion

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