-2

Here's my list:

myList =
 ["HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","CALL_TO_ACTION"]

I would like to have some logic in place that would help me divide myList into below three sub-lists (stored as, say, List<List<String> subLists):

["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","CALL_TO_ACTION"]

Please note, the number three comes from the number of occurrences of the element "HEADING" (which I could find out using Collections.frequency(myList, "HEADING")).

Akshay Maldhure
  • 787
  • 2
  • 19
  • 38
  • Possible duplicate of [Java: how can I split an ArrayList in multiple small ArrayLists?](https://stackoverflow.com/questions/2895342/java-how-can-i-split-an-arraylist-in-multiple-small-arraylists) – Shubhendu Pramanik Dec 07 '17 at 05:36
  • 1
    @ShubhenduPramanik I don't think it's a duplicate. The post you are referring is about subList creation with a specific length. – Zerthimon Dec 07 '17 at 06:52

1 Answers1

3

One way to do this is,

Step 1: Collect all the indices from your myList where "HEADING" appears.

List<Integer> indexList = new ArrayList<>();
    for(int index = 0; index < list.size(); index++) {
        if(list.get(index).equals("HEADING"))
            indexList.add(index);
    }

Step 2: Iterate through this indexList and create sub lists by using current index and the next index.

for(int builderIndex = 0; builderIndex < indexList.size(); builderIndex++) {
    List<String> test = null;
    if(builderIndex == indexList.size() - 1) {
        test = list.subList(indexList.get(builderIndex), list.size());
    } else {
        test = list.subList(indexList.get(builderIndex), indexList.get(builderIndex + 1));
    }
    System.out.println(test);
} 

Boundary condition is to check if the current index is equal to one less than the size of the indexList. If yes, then the end index of the sub list would be the size of the original list.

I hope this helps.

Shyam Baitmangalkar
  • 1,075
  • 12
  • 18
  • I can't think of a way to avoid loops, since the sublists don't have a constant length. Apache Commons Collections 4.1 and Google Guava provide an easy solution in case of constant sublist length. – Zerthimon Dec 07 '17 at 06:45
  • 1
    Yes, I've used as minimal loops as possible. The running time of this code would be `~n+m` where `n` is the length of original list and `m` is the length of index list. – Shyam Baitmangalkar Dec 07 '17 at 06:55
  • Thank you @ShyamBaitmangalkar, your solution helps. I've modified it slightly to suit my requirement so that it gives me a `List>` instead of `List`. – Akshay Maldhure Dec 07 '17 at 07:55
  • 1
    @AkshayMaldhure, I'm glad that it's been helpful! – Shyam Baitmangalkar Dec 07 '17 at 07:57