Explain Codes LogoExplain Codes Logo

Java: how can I split an ArrayList in multiple small ArrayLists?

java
list-manipulation
stream-api
guava
Alex KataevbyAlex Kataev·Sep 21, 2024
TLDR

Easily chop your ArrayList into smaller chunks using the subList method. Below is a rock-solid yet concise snippet that does this, where size is the length of each segment:

List<List<Integer>> choppedLists = new ArrayList<>(); int size = 3; // The magic number that determines the destiny of your new lists for (int i = 0; i < list.size(); i += size) { choppedLists.add(new ArrayList<>(list.subList(i, Math.min(list.size(), i + size)))); }

Feel free to twiddle with size for differently sized sublists.

Transforming sublists into independent lists

When you want independence for your sublists, the revolution is quick, create new instances of ArrayList:

List<ArrayList<Integer>> independentLists = choppedLists.stream() .map(ArrayList::new) // The clone factory .collect(Collectors.toList());

Residual elements - Oh, the horror!

Worry not, I have a solution for when your list's size does not perfectly divide by the sublist's chosen size. This handles the remainders efficiently:

int remainder = list.size() % size; if(remainder != 0) { choppedLists.add(new ArrayList<>(list.subList(list.size() - remainder, list.size()))); }

Remember, remainders, like forgotten birthday dates, can cause unexpected surprises.

Leveraging libraries

Partitioning like a boss with Guava

Guava is your friend when you love conciseness:

List<List<Integer>> guavaPartitions = Lists.partition(originalList, size);

Splitting in elegance with Apache Commons Collections

Apache Commons Collections has a gorgeous way to split ArrayLists too:

List<List<Integer>> apachePartitions = ListUtils.partition(originalList, size);

Cruising with Java 8 Stream API

With Java 8 Streams, there is no limit! It's like the Bugatti of ArrayList partitioning:

AtomicInteger index = new AtomicInteger(); Collection<List<Integer>> streamPartitions = originalList.stream() .collect(Collectors.groupingBy(it -> index.getAndIncrement() / size)) .values();