i want to convert from List<List<Integer>>
to List<int[]>
but i don't know how to do it.
I try to do it :
List<Integer> list = new ArrayList<>();
List<List<Integer>> arr = matrix(list);
int [] temp2 = arr;
But it was wrong
i want to convert from List<List<Integer>>
to List<int[]>
but i don't know how to do it.
I try to do it :
List<Integer> list = new ArrayList<>();
List<List<Integer>> arr = matrix(list);
int [] temp2 = arr;
But it was wrong
I am not sure what you really want to achieve, but a simple solution would be a double loop to convert each List<Integer>
to int[]
. And you can do it with a simple method as AFAIK there is no built-in library doing this for you (because of the heterogeneity of types List
and int[]
):
// cycle this for each List<Integer>
int[] toIntArray(List<Integer> a_list){
int[] ret = new int[a_list.size()];
for(int i = 0; i < ret.length; i++)
ret[i] = a_list.get(i);
return ret;
}
Update Java 8
Thanks to Java 8 streams now you can simply write (again the example is for a single List<Integer>
:
int [] my_ints = list.stream().mapToInt(Integer::intValue).toArray();
Update
As you asked for the complete solution, I will write down a possible method to achieve what you need:
List<int[]> intArrayList = new ArrayList();
for(List<Integer> intList : intListList){
int[] intArray = new int[intList.size()];
for(int i = 0; i < intArray.length; ++i){
intArray[i] = intList.get(i);
}
intArrayList.add(intArray);
}
i want to convert from List<List<Integer>> to List<int[]>
The return value from matrix() that you called arr for some reason is called intListList below.
// You can map the List<Integer> items in the List<List<Integer> to int[] items in a List<int[]> like so:
List<int[]> intArrList = intListList.stream()
.map(Collection::stream)
.map(Stream::mapToInt)
.map(IntStream::toArray)
.collect(Collectors.toList())
// or if you prefer
List<int[]> intArrList = intListList.stream()
.map(ints -> ints.stream().mapToInt().toArray())
.collect(Collectors.toList())
// For Java before 8
List<int[]> intArrList = new ArrayList();
for(List<Integer> ints : intListList){
int[] intArr = new int[ints.size()];
for(int i = 0; i < intArr.length; ++i){
intArr[i] = ints.get(i);
}
intArrList.add(intArr);
}
> to List ?