EN
Java - convert double[] to List<Double> - primitive double array to list of objects
7 points
Problem description
xxxxxxxxxx
1// We have:
2double[] arr = {1.2, 2.7, 3.9};
3// And we want to convert this array to list:
4List<Double> list; // [1.2, 2.7, 3.9]
xxxxxxxxxx
1
double[] arr = {1.2, 2.7, 3.9};
2
List<Double> list = DoubleStream.of(arr).boxed().collect(Collectors.toList());
3
System.out.println(list); // [1.2, 2.7, 3.9]
Output:
xxxxxxxxxx
1
[1.2, 2.7, 3.9]
Return required implementation eg ArrayList
or HashSet
xxxxxxxxxx
1
double[] arr = {1.2, 2.7, 3.9};
2
ArrayList<Double> list = DoubleStream.of(arr).boxed()
3
.collect(Collectors.toCollection(ArrayList::new));
4
System.out.println(list); // [1.2, 2.7, 3.9]
Output:
xxxxxxxxxx
1
[1.2, 2.7, 3.9]
xxxxxxxxxx
1
double[] arr = {1.2, 2.7, 3.9};
2
List<Double> list = new ArrayList<>();
3
for (double no : arr) {
4
list.add(Double.valueOf(no));
5
// we can also just add primitive double
6
}
7
System.out.println(list); // [1.2, 2.7, 3.9]
Output:
xxxxxxxxxx
1
[1.2, 2.7, 3.9]
xxxxxxxxxx
1
double[] arr = {1.2, 2.7, 3.9};
2
List<Double> list = Doubles.asList(arr);
3
System.out.println(list); // [1.2, 2.7, 3.9]
Output:
xxxxxxxxxx
1
[1.2, 2.7, 3.9]
xxxxxxxxxx
1
double[] arr = {1.2, 2.7, 3.9};
2
Double[] doubleArray = ArrayUtils.toObject(arr);
3
List<Double> list = Arrays.asList(doubleArray);
4
System.out.println(list); // [1.2, 2.7, 3.9]
Output:
xxxxxxxxxx
1
[1.2, 2.7, 3.9]
- Best solution -
DoubleStream.of
(Java 8) DoubleStream.of
+ return ArrayList (Java 8)- Explicit iteration over array (before Java 8)
Doubles.asList
(Guava)ArrayUtils.toObject
(Apache commons lang3)