How to split an ArrayList into sublists (list of lists) by checking a condition on elements in Java

1 Answer

0 votes
import java.util.ArrayList;
import java.util.List;

public class SplitArrayListIntoSublistsByCondition_Java {
    public static List<List<Integer>> SplitArrayListIntoSublistsByCondition(List<Integer> lst, int condition) {
        List<List<Integer>> listOfListsByZero = new ArrayList<>();
        listOfListsByZero.add(new ArrayList<>());

        for (Integer value : lst) {
            listOfListsByZero.get(listOfListsByZero.size() - 1).add(value);
            if (value == condition) {
                listOfListsByZero.add(new ArrayList<>());
            }
        }
        
        return listOfListsByZero;
    }
    
    public static void main(String[] args) {
        List<Integer> lst = new ArrayList<Integer>() {{
            add(1);
            add(2);
            add(3);
            add(0);
            add(4);
            add(5);
            add(6);
            add(7);
            add(0);
            add(8);
            add(9);
            add(10);
        }};
        
        List<List<Integer>> listOfListsByZero = SplitArrayListIntoSublistsByCondition(lst, 0);

        for (List<Integer> subList : listOfListsByZero) {
            for (Integer elements : subList) {
                System.out.println(elements);
            }
            System.out.println();
        }
    }
}



/*
run:

1
2
3
0

4
5
6
7
0

8
9
10

*/

 



answered Oct 29, 2024 by avibootz
...