To split a list in Java, you can use the subList
method of the List
interface or manually create chunks.
In this example,
numbers
with initial integer values.subList
method to create a sublist from the original list, specifying the start and end indices.subList
method returns a view of the specified range within the original list.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 6; i++) {
numbers.add(i);
}
List<Integer> sublist = numbers.subList(2, 5);
System.out.println("Sublist: " + sublist);
}
}
Sublist: [3, 4, 5]
In this example,
numbers
with initial integer values.splitList
that takes a list and a chunk size as parameters.splitList
method, we use a for loop to iterate over the list and create sublists of the specified chunk size.import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 8; i++) {
numbers.add(i);
}
List<List<Integer>> chunks = splitList(numbers, 3);
System.out.println("Chunks: " + chunks);
}
public static List<List<Integer>> splitList(List<Integer> list, int chunkSize) {
List<List<Integer>> chunks = new ArrayList<>();
for (int i = 0; i < list.size(); i += chunkSize) {
int end = Math.min(list.size(), i + chunkSize);
chunks.add(new ArrayList<>(list.subList(i, end)));
}
return chunks;
}
}
Chunks: [[1, 2, 3], [4, 5, 6], [7, 8]]
In this tutorial, we learned How to Split a List in Java language with well detailed examples.