dominono
dominono

Reputation: 25

How do I split Arraylist into several Arraylists?

I am trying to split the Arraylist into numbers of Arraylists with the rule:

For example, if there is an arraylist {6,7,8,3,9,10,1,4}, it should be stored as { {6,7,8}, {3,9,10}, {1,4} }.

How can I do this one?

Upvotes: 1

Views: 1010

Answers (3)

Veera
Veera

Reputation: 41

public static void splitList(ArrayList<Integer> input) {
        ArrayList<ArrayList<Integer>> output = new ArrayList<ArrayList<Integer>>();
        System.out.println("Input : "+input);
        for (int count = 0; count < input.size(); count++) {

            ArrayList<Integer> subList = new ArrayList<Integer>();
            for (int index = count; index < input.size(); index++) {
                if((index == input.size() - 1) || (input.get(index) > input.get(index + 1))){
                    subList.add(input.get(index));
                    count = index;
                    break;
                }else {
                    subList.add(input.get(index));
                }
            }
            output.add(subList);
        }
        System.out.println("Output : "+output);
    }

Upvotes: 1

Amir Reza Mohammadi
Amir Reza Mohammadi

Reputation: 76

This code should work for you

        List<Integer> mainList = new ArrayList<>();
        List<List<Integer>> listOfLists = new ArrayList<>();
        int listIndex = 0;
        for (int i = 0; i < mainList.size(); i++) {
            if (i == 0) {
                listOfLists.add(new ArrayList<>());
            } else if (mainList.get(i) < mainList.get(i - 1)) {
                listOfLists.add(new ArrayList<>());
                listIndex++;
            }
            listOfLists.get(listIndex).add(mainList.get(i));
        }

Upvotes: 1

Ctrain
Ctrain

Reputation: 36

By looping through the original arraylist and using the sublist method the below code should solve your problem.

    ArrayList<ArrayList<Integer>> lists = new ArrayList<ArrayList<Integer>>();
    ArrayList<Integer> numbers = new ArrayList<>(Arrays.asList(6,7,8,3,9,10,1,4));

    int indexToSplitFrom = 0;
    for(int i = 0; i < numbers.size() - 1; i++){
        System.out.println(numbers.get(i));
        if(numbers.get(i) > numbers.get(i+1)){
            lists.add(new ArrayList<>(numbers.subList(indexToSplitFrom, i + 1)));
            indexToSplitFrom = i + 1;
        }
    }
    lists.add(new ArrayList<>(numbers.subList(indexToSplitFrom,  + numbers.size())));

Upvotes: 2

Related Questions