3

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
2

4 Answers 4

1

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)));
}
Sign up to request clarification or add additional context in comments.

Comments

1

The Guava library has Lists#partition.

Returns consecutive sublists of a list, each of the same size (the final list may be smaller). For example, partitioning a list containing [a, b, c, d, e] with a partition size of 3 yields [[a, b, c], [d, e]] -- an outer list containing two inner lists of three and two elements, all in the original order.

1 Comment

@sujay. I have to store it and dispaly
0

You can use list.subList(from, to) and calculate from and to using passed value.

Comments

0

As we know the fact that list is cutted on every second element you can something like this.

public class Testing {

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

public Testing() {
    for (int i = 0; i < messages.size(); i++) {
        lists.add(getPartOfList(i));
        i++;
    }
}

private List<String> getPartOfList(int index){
    List<String> tmp = new ArrayList<String>();
    int counter = 0;

    while(counter != 2){
        if(messages.size() > index)
            tmp.add(messages.get(index));
        index++;
        counter++;
    }

    System.out.println(tmp);
    return tmp;
}

public static void main(String[] args) {
    new Testing();
}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.