0

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

2
  • When you write 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. Commented Jul 27, 2021 at 11:40
  • You can define the size of the sub lists when creating it like new ArrayList<>(2);. Commented Jul 27, 2021 at 11:47

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

You are creating an empty list on each iteration, then you check if its size != 2 (of course it is) and add 1 element, finally you add list with 1 element to result list, which is not what you need.

Move list creation out of loop and add elements to it. When its size == 2, add current list to result list and create a new one.

class ListList {
    public static List<List<Integer>> listOfList(int[] num) {
        List<List<Integer>> arrList = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        for(int i = 0; i < num.length; i++) {
            if(list.size() == 2) {
                arrList.add(list);
                list = new ArrayList<>();
            }
            list.add(num[i]);
        }
        if(list.size() != 0) {
            arrList.add(list);
        }
        return arrList;
    }
}

If your input size can be odd, then you would also add list of length 1 to result list. If you don't want to, add aditional checks.

1 Comment

it results [[3, 1], [8, 2]].why?
1

If you're certain that the list has an even number of values, you can do it like this.

  • create a list of lists.
  • taking two at a time, put each in a separate list
  • add that list to the list of lists
int [] arr ={3, 1, 5, 8, 2, 4};
List<List<Integer>> list = new ArrayList<>();
for (int i = 0; i < arr.length; i+=2) {
    List<Integer> temp = Arrays.asList(arr[i], arr[i+1]);
    list.add(temp);
}
    
System.out.println(list);

prints

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

If you list is of odd length, change the assignment to

List<Integer> temp = arr.length - i >= 2 ? Arrays.asList(arr[i], arr[i+1]) :
                                            Arrays.asList(arr[i]);

And here is a different take on the idea suggested by Dhrubajyoti Gogoi.

  • stream the indices.
  • use integer math to divide into groups, mapping to a list
  • and return the values as a collection of lists.
int groupSize = 2;
Collection<List<Integer>> result =
        IntStream.range(0, arr.length)
                .mapToObj(Integer::valueOf)
                .collect(Collectors.groupingBy(
                        i -> i / groupSize,
                        Collectors.mapping(i -> arr[i],
                                Collectors.toList())))
                .values();

2 Comments

Thats way cleaner @WJS!! 👍
@DhrubajyotiGogoi But it's the idea that is key! +1
0

Try this:

public static List<List<Integer>> listOfList(int[] num){
    List<List<Integer>> arrList = new ArrayList<>();
    for (int i = 0; i < num.length; i += 2) {
        if (num.length > i + 1) {
            arrList.add(List.of(num[i], num[i+1]));
        } else {
            arrList.add(List.of(num[i]));
        }
    }

    return arrList;
}

In your example you always create a fresh list in the loop, so size is always 0 and never 2.

2 Comments

How can i modify so that A new list is created when num[i] is greater than previus element.eg {5,4,3,6,1,2} would be [[5,4,3],[6,1],[2]]?
@AlanKm Please don't ask follow on questions that augment the original question. Just ask a new question. But remember to post your attempt. Remember that others may look at this and find that the second question is of more value than the first. So let the second question stand on its own.