home / blog

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)));
}
This entry was posted in geek and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.