3 回答
TA贡献1810条经验 获得超5个赞
这是一种使用循环Comparable在分隔符上“拆分” s列表的方法:
private static <T extends Comparable<T>> List<List<T>> split(
List<T> original, T delimiter) {
List<List<T>> res = new ArrayList<>();
List<T> current = new ArrayList<>();
for (T f : original) {
if (f.compareTo(delimiter) == 0) {
res.add(current);
current = new ArrayList<>();
continue;
}
current.add(f);
}
if (!current.isEmpty()) {
res.add(current);
}
return res;
}
它[[a, b, c, d, e, f], [g, h]]在测试时返回:
public static void main(String[] args) throws Exception {
List<String> list =
Arrays.asList("a", "b", "c", "d", "e", "f", "PASS", "g", "h");
System.out.println(split(list, "PASS"));
}
TA贡献1780条经验 获得超5个赞
这可以写为通用方法(我已经在我的 stackoverflow 答案中使用了它,所以我想我以前在某处读过这个......我会尝试找到具体的位置):
private static <T> List<List<T>> splitBy(List<T> list, T delimiter) {
int[] indexes = IntStream.rangeClosed(-1, list.size())
.filter(i -> i == -1
|| i == list.size()
|| delimiter.equals(list.get(i))).toArray();
return IntStream.range(0, indexes.length - 1)
.mapToObj(x -> list.subList(indexes[x] + 1, indexes[x + 1]))
// or since java-11, a bit nicer:
// .filter(Predicate.not(List::isEmpty))
.filter(l -> !l.isEmpty())
.collect(Collectors.toList());
}
TA贡献1862条经验 获得超6个赞
我安排了简单的解决方案,检查这是否适合您。谢谢你。
/**
* @author Duminda Hettiarachchi
*/
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class StringSubList {
ArrayList<String> subList;
public StringSubList() {
subList = new ArrayList<String>();
}
public void subList(List<String> list) {
int passIndex = list.indexOf("PASS");
List<String> list1 = (List<String>) list.subList(0, passIndex);
List<String> list2 = (List<String>) list.subList(passIndex+1, list.size());
List<List<String>> subLists = new ArrayList<List<String>>();
subLists.add(list1);
subLists.add(list2);
System.out.println("List 1 :" + subLists.get(0));
System.out.println("List 2 : " + subLists.get(1));
}
public static void main(String[] args) {
String mainArr[] = {"a", "b", "c", "d", "e", "f", "PASS", "g", "h"};
List<String> myList = Arrays.asList("a", "b", "c", "d", "e", "f", "PASS", "g", "h");
new StringSubList().subList(myList); `enter code here`
}
}
输出 :
列表 1 :[a, b, c, d, e, f]
列表 2 : [g, h]
添加回答
举报