Hey everyone,
When I started to leetcode, i have logic to solve in mind but I always google how to convert List into Array because return type will be int[] or int[][] but solution will be handy to use java collections utils :p . If you are also the one same as me, This might help you in some places.
Of Course converting list to array using streams is one liner. If you are new to java, remembering this is not so easy until you practice.
Here is our array list,
List<Integer> myList = new ArrayList<>();
myList.add(11);
myList.add(12);
Let us convert then into integer array,
int[] arr = list.stream().mapToInt(i->i).toArray(); or list.stream().mapToInt(Integer:: intValue).toArray();
If not using streams, I use a for loop to iterate over list elements and dump into actual array. This was yuck... I assume this is trivial to be known.
Another way could be as below, which is not often useful for int arrays, but for strings
Integer[] arr = list.toArray(new Integer[list.size()]);
This will not work if we use primitive data type like int. Of course above might help for converting list of Strings to array of strings,
Everything becomes interesting when it is a 2D array. In some problems, it is expected to return a int[][]
but things will be easy if we use List<List> , In this case below will be helpful.
List<List> eg: List<int []> myList= new ArrayList<>();myList.add(new int[] {1,2});int[][],return myList.toArray(new int[myList.size()][]);