Languages
[Edit]
PL

Java - przekonwertuj double[] na List<Double> - pierwotna podwójna tablica na list─Ö obiektów

6 points
Created by:
Sylwia
1334

Opis problemu

// Mamy:
double[] arr = {1.2, 2.7, 3.9};
// Chcemy przekonwertowa─ç t─Ö tablic─Ö na list─Ö:
List<Double> list; // [1.2, 2.7, 3.9]

1. Najlepsze rozwi─ůzanie - 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]

Wynik:

[1.2, 2.7, 3.9]

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

Zwrot wymaganej implementacji np ArrayList lub 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]

Wynik:

[1.2, 2.7, 3.9]

3. Jawna iteracja po tablicy (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]

Wynik:

[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]

Wynik:

[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]

Wynik:

[1.2, 2.7, 3.9]

Podsumowanie - w Javie mo┼╝emy zamieni─ç double[] na List<Double> przez:

  1. Najlepsze rozwi─ůzanie - DoubleStream.of (Java 8)
  2. DoubleStream.of + zwrot ArrayList (Java 8)
  3. Jawna iteracja po tablicy (before Java 8)
  4. Doubles.asList (Guava)
  5. ArrayUtils.toObject (Apache commons lang3)

Bibliografia

  1. DoubleStream.of - Java 8 docs
  2. Doubles.asList - Guava docs
  3. ArrayUtils.toObject - Apache commons lang3 docs
Hey ­čĹő
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.