Konwersja 'ArrayList do' String [] ' w Javie
Jak mogę przekonwertować obiekt ArrayList<String>
Na tablicę String[]
w Javie?
17 answers
List<String> list = ..;
String[] array = list.toArray(new String[0]);
Na przykład:
List<String> list = new ArrayList<String>();
//add some stuff
list.add("android");
list.add("apple");
String[] stringArray = list.toArray(new String[0]);
Metoda toArray()
bez podania argumentu zwraca Object[]
. Więc musisz przekazać tablicę jako argument, który zostanie wypełniony danymi z listy i zwrócony. Można również przekazać pustą tablicę, ale można również przekazać tablicę o pożądanym rozmiarze.
Ważna aktualizacja : pierwotnie powyższy kod używał new String[list.size()]
. Jednak ten blogpost ujawnia, że dzięki optymalizacjom JVM, używanie new String[0]
jest teraz lepsze.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-11 17:28:30
Alternatywa w Javie 8:
String[] strings = list.stream().toArray(String[]::new);
Java 11+:
String[] strings = list.toArray(String[]::new);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-21 01:20:39
Możesz użyć metody toArray()
dla List
:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = list.toArray(new String[list.size()]);
Lub można ręcznie dodać elementy do tablicy:
ArrayList<String> list = new ArrayList<String>();
list.add("apple");
list.add("banana");
String[] array = new String[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Mam nadzieję, że to pomoże!Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-27 17:41:08
ArrayList<String> arrayList = new ArrayList<String>();
Object[] objectList = arrayList.toArray();
String[] stringArray = Arrays.copyOf(objectList,objectList.length,String[].class);
Używając copyOf, ArrayList to arrays można również wykonać.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-22 05:15:09
Począwszy od Java-11, można alternatywnie użyć API Collection.toArray(IntFunction<T[]> generator)
aby osiągnąć to samo co:
List<String> list = List.of("x","y","z");
String[] arrayBeforeJDK11 = list.toArray(new String[0]);
String[] arrayAfterJDK11 = list.toArray(String[]::new); // similar to Stream.toArray
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-26 00:56:18
W Javie 8:
String[] strings = list.parallelStream().toArray(String[]::new);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-05 15:54:26
W Javie 8 można to zrobić za pomocą
String[] arrayFromList = fromlist.stream().toArray(String[]::new);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 12:53:06
Jeśli Twoja aplikacja korzysta już z Apache Commons lib, możesz nieznacznie zmodyfikować zaakceptowaną odpowiedź, aby nie tworzyć nowej pustej tablicy za każdym razem:
List<String> list = ..;
String[] array = list.toArray(ArrayUtils.EMPTY_STRING_ARRAY);
// or if using static import
String[] array = list.toArray(EMPTY_STRING_ARRAY);
Jest jeszcze kilka wstępnie przydzielonych pustych tablic różnych typów w ArrayUtils
.
Możemy również oszukać JVM, aby utworzyć dla nas pustą tablicę En w ten sposób:
String[] array = list.toArray(ArrayUtils.toArray());
// or if using static import
String[] array = list.toArray(toArray());
Ale tak naprawdę nie ma żadnej przewagi, tylko kwestia gustu, IMO.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-14 13:16:47
Możesz użyć Iterator<String>
do iteracji elementów ArrayList<String>
:
ArrayList<String> list = new ArrayList<>();
String[] array = new String[list.size()];
int i = 0;
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); i++) {
array[i] = iterator.next();
}
Teraz możesz pobierać elementy z {[3] } za pomocą dowolnej pętli.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-04 13:22:52
Generics rozwiązanie do ukrycia dowolnego List<Type>
do String []
:
public static <T> String[] listToArray(List<T> list) {
String [] array = new String[list.size()];
for (int i = 0; i < array.length; i++)
array[i] = list.get(i).toString();
return array;
}
Uwaga Musisz override toString()
metoda.
class Car {
private String name;
public Car(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
final List<Car> carList = new ArrayList<Car>();
carList.add(new Car("BMW"))
carList.add(new Car("Mercedes"))
carList.add(new Car("Skoda"))
final String[] carArray = listToArray(carList);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-04 13:23:52
List <String> list = ...
String[] array = new String[list.size()];
int i=0;
for(String s: list){
array[i++] = s;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-10-28 12:58:15
W przypadku, gdy pożądana jest jakaś dodatkowa manipulacja danymi, dla której użytkownik chce funkcji, takie podejście nie jest idealne (ponieważ wymaga podania klasy elementu jako drugiego parametru), ale działa:
Import Javy.util.ArrayList; Importuj Javę.lang.zastanów się.Array;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<>();
al.add(1);
al.add(2);
Integer[] arr = convert(al, Integer.class);
for (int i=0; i<arr.length; i++)
System.out.println(arr[i]);
}
public static <T> T[] convert(ArrayList<T> al, Class clazz) {
return (T[]) al.toArray((T[])Array.newInstance(clazz, al.size()));
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-04 22:37:00
W Javie 11 możemy użyć metody Collection.toArray(generator)
. Poniższy kod utworzy nową tablicę łańcuchów:
List<String> list = List.of("one", "two", "three");
String[] array = list.toArray(String[]::new)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-17 19:18:41
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
String [] strArry= list.stream().toArray(size -> new String[size]);
Za komentarze, dodałem akapit, aby wyjaśnić, jak działa konwersja. Po pierwsze, lista jest konwertowana do strumienia Łańcuchowego. Następnie używa strumienia.ToArray do konwersji elementów w strumieniu do tablicy. W ostatniej instrukcji powyżej "size- > new String [size]" Jest w rzeczywistości funkcją IntFunction, która przydziela tablicę łańcuchów o rozmiarze strumienia łańcuchów. Twierdzenie jest identyczne z
IntFunction<String []> allocateFunc = size -> {
return new String[size];
};
String [] strArry= list.stream().toArray(allocateFunc);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2019-11-25 19:28:15
Możesz przekonwertować listę do tablicy łańcuchowej za pomocą tej metody:
Object[] stringlist=list.toArray();
Pełny przykład:
ArrayList<String> list=new ArrayList<>();
list.add("Abc");
list.add("xyz");
Object[] stringlist=list.toArray();
for(int i = 0; i < stringlist.length ; i++)
{
Log.wtf("list data:",(String)stringlist[i]);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-26 18:21:57
private String[] prepareDeliveryArray(List<DeliveryServiceModel> deliveryServices) {
String[] delivery = new String[deliveryServices.size()];
for (int i = 0; i < deliveryServices.size(); i++) {
delivery[i] = deliveryServices.get(i).getName();
}
return delivery;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-27 09:28:01
Mamy następujące trzy sposoby konwersji arraylist do array
-
Public T[] ToArray (T[] a) - w ten sposób utworzymy tablicę o rozmiarze listy, a następnie wstawimy metodę jako String [] arr = new String [list.size ()];
Arr = lista.toArray (arr);
-
Public get () metoda - w ten sposób iterujemy listę i wstawiamy element do tablicy jeden po drugim
Odniesienie : Jak przekonwertować ArrayList do tablicy w Javie
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-01-27 08:49:43