Divide a list into sublists in Java



Sometimes you have large lists that you need to divide into sublists due to different reasons. One reason could be that you need to make a query to a database with all the values in an IN-clause, but the database has a limit to how many elements you can provide in that case. Then you might want to make several IN-clauses separated by OR. In such a case you need to divide your list into sublists and this example shows one way to do it.

This example uses generics so the list can contain any type of objects. In this case we use a list of Long-values. We create a list using the Random class to randomly generate 3005 values to add to the list.
Then we call the toSublists method passing the list we just created along with a max size value of each sublist. In this case we have a static final variable called SUBLIST_MAX_SIZE that is set to 1000.

The return value from that method is a List where each element is a sublist of the original list. Finally we just print out the length of each sublist. Below is the code just explained:

The output from the code above will show that 3 sublists contains the max value of 1000 elements and the final sublist will contain 5 elements.







Search for more Java info on this site here:
Custom Search


Please type any questions here.