How can i create a list of List from Array eg:
int[] arr = {3, 1, 5, 8, 2, 4}.
Such that the lists in the List have only two elements eg:
[[3,1], [5,8], [2,4]].
So far i have tried code below but it return only lists with one element,I can't figure out where i went wrong.
class ListList {
public static List<List<Integer>> listOfList(int[] num){
List<List<Integer>> arrList = new ArrayList<>();
for(int i = 0 ; i<num.length;i++){
List<Integer> list = new ArrayList<>();
if(list.size() !=2){
list.add(num[i]);
}
arrList.add(list);
}
return arrList;
}
}
Result: [[3], [1], [5], [8], [2], [4]].
List<Integer> list = new ArrayList<>();, you're creating a new list at every iteration of the loop. So your size check is redundant, it will always be empty. I would recommend incrementing by two and adding both elements to a list in a single iteration.new ArrayList<>(2);.