DE
Java - convert double[] to List<Double> - primitive Double-Array in Objektliste
3
points
Problembeschreibung
// Wir haben: double[] arr = {1.2, 2.7, 3.9}; // Und wir wollen diese Array in eine List konvertieren: List<Double> list; // [1.2, 2.7, 3.9]
1. Die beste Lösung - 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]
Ausgabe:
[1.2, 2.7, 3.9]
2. DoubleStream.of
+ ArrayList zurückgeben (Java 8)
Rückgabe der erforderlichen Implementierung z.B. ArrayList
oder 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]
Ausgabe:
[1.2, 2.7, 3.9]
3. Explizite Iteration über 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]
Ausgabe:
[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]
Ausgabe:
[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]
Ausgabe:
[1.2, 2.7, 3.9]
Zusammenfassung - in Java kann man folgendens double[] in List<Double> konvertieren:
- Die beste Lösung -
DoubleStream.of
(Java 8) DoubleStream.of
+ ArrayList zurückgeben (Java 8)- Explizite Iteration über Array (before Java 8)
Doubles.asList
(Guava)ArrayUtils.toObject
(Apache commons lang3)