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
Manu
  • 3,179
  • 23
  • 57
  • 69
  • Do you have to store or do you've to display only? – Sujay Aug 29 '12 at 07:11
  • possible duplicate of [Java: how can I split an ArrayList in multiple small ArrayLists?](http://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists) – Thilo Aug 29 '12 at 07:13

4 Answers4

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.

Thilo
  • 257,207
  • 101
  • 511
  • 656
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)));
}
Adam
  • 35,919
  • 9
  • 100
  • 137
0

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

Amit Deshpande
  • 19,001
  • 4
  • 46
  • 72
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();
}
}
Dusean Singh
  • 1,456
  • 2
  • 15
  • 20