How to convert List <Integer> to Integer [] in java?
5 answers
You cannot use Listfor an array because it is Listnot an array. Here are two methods for converting a List<Integer>to Integer[].
List<Integer> list = Arrays.asList(1, 2, 3);
Integer[] arr = list.toArray(new Integer[list.size()]);
Integer[] arr2 = list.stream().toArray(Integer[]::new); // Java 8 only
+5
List.toArray() . List.toArray(T []):
Integer[] finalResult = (Integer[]) result.toArray(new Integer[result.size()]);
+2
You can do this in several ways:
1st method
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Example:
List<String> list = new ArrayList<String>();
list.add("India");
list.add("Switzerland");
list.add("Italy");
list.add("France");
String [] countries = list.toArray(new String[list.size()]);
Second method
Foo[] array = new Foo[list.size()];
list.toArray(array); // fill the array
Third method
List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
You can also find some code examples here - http://www.tutorialspoint.com/java/util/arraylist_toarray.htm or http://examples.javacodegeeks.com/core-java/util/list/java-list-to -array-example /
+2