这是我的清单:
myList =
["HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","POST","CALL_TO_ACTION","HEADING","POST","POST","CALL_TO_ACTION"]
我希望有一些逻辑可以帮助我将myList
划分为以下三个子列表(存储为List<List<String> subLists
):
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","POST","CALL_TO_ACTION"]
["HEADING","POST","POST","CALL_TO_ACTION"]
请注意,数字3来自元素"HEADING"
的出现次数(我可以使用Collections.frequency(myList, "HEADING")
找到)。
答案 0 :(得分:2)
一种方法是,
第1步:从exit
收集“HEADING”出现的所有索引。
myList
第2步:遍历此List<Integer> indexList = new ArrayList<>();
for(int index = 0; index < list.size(); index++) {
if(list.get(index).equals("HEADING"))
indexList.add(index);
}
并使用当前索引和下一个索引创建子列表。
indexList
边界条件是检查当前索引是否等于小于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);
}
的大小。如果是,那么子列表的结束索引将是原始列表的大小。
我希望这会有所帮助。