Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to split list of strings into multiple list dynamically in java

Tags:

java

I want to split list of strings into multiple list based on input value dynamically using java program.

For eg. If Im having the below list of string

     List<String> messages = Arrays.asList("Hello", "World!", "How", "Are", "You");

I have to split the list of string into multiple lists with the condtion if i entered 2 as input value each splited list should contain 2 values in it.

Note: How many values the list should contain be based on input value

       outputshould be: 
       list1 contains-> Hello,world
       list2 contains -> How,Are
       list3 contains -> you
like image 324
Manu Avatar asked Sep 12 '26 07:09

Manu


1 Answers

As another answer suggests List.subList() is the easiest way. I'd use Math.min to cover the last partition case.

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)));
}
like image 84
Adam Avatar answered Sep 13 '26 21:09

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!