Skip to content
Advertisement

Create a list of List from an Array

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]].

Advertisement

Answer

Here’s a generic one:

var arr = new int[] {3, 1, 5, 8, 2, 4};
var batchSize = 2;
List<List<Integer>> lists = IntStream.range(0, arr.length)
        .mapToObj(index -> Map.entry(index, arr[index]))
        .collect(Collectors.groupingBy(e -> e.getKey() / batchSize))
        .values().stream()
        .map(entries -> entries.stream().map(Map.Entry::getValue).toList())
        .toList();
System.out.println(lists);

Output:

[[3, 1], [5, 8], [2, 4]]

You are basically creating a mapping of index->value and subsequently grouping by the batchSize to make splits

Advertisement