List partitioning

I’ve seen this done so many times in different ways, the easiest is definitely using subList. Note how use of Math.min removes need for a if statement.

int partitionSize = 2;
List<List<String>> partitions = new LinkedList<List<String>>();
for (int i = 0; i < messages.size(); i += partitionSize) {
    partitions.add(messages.subList(i,
            i + Math.min(partitionSize, messages.size() - i)));
}
Published
Categorized as geek Tagged

Leave a comment

Your email address will not be published.