在java中从列表中删除一个项目序列

au9on6nz  于 2023-03-06  发布在  Java
关注(0)|答案(2)|浏览(123)

我有一个用java写的字符串数组列表,可视化后,看起来像这样:

"Some text"
"Some more text"
""
"Line a"
"Line b"
...
""
"Line c"
"Line d"

在这个列表中,我想一起删除三元组"", "Line c", and "Line d",所以列表看起来像

"Some text"
"Some more text"
""
"Line a"
"Line b"
...

我不知道该怎么做。如果我只删除每一行的第一次出现,a行之前的空行也会被删除。同样,c行可能等于a行或b行,但它不应该被删除,除非它前面是空行,后面是d行,所以删除的项目需要正好是这3个项目。完全按照这个顺序。有什么办法我可以做到这一点吗?提前感谢。

11dmarpk

11dmarpk1#

使用Collections.lastIndexOfSubList检查列表是否包含子列表,如果它确实获得了最后一个索引,则删除从最大索引开始向后迭代的元素:

List<String> list = new ArrayList<>(List.of("Some text",
                                            "Some more text",
                                            "",
                                            "Line a",
                                            "Line b",
                                            "",
                                            "Line c",
                                            "Line d"));

List<String> target = List.of("", "Line c", "Line d");

while (Collections.lastIndexOfSubList(list, target) != -1) {
    int lastIndex = Collections.lastIndexOfSubList(list, target);
    for (int i = target.size() - 1; i >= 0; i--) {
        list.remove(lastIndex + i);
    }
}
amrnrhlw

amrnrhlw2#

只需检查接下来的3个值,以确定是否需要保留它们

List<String> a = new ArrayList<>(List.of("Some text", "Some more text",
        "", "Line a", "Line b",
        "", "Line c", "Line d",
        "Line a", "Line b",
        "", "Line c", "Line d"));
for (int i = 0; i < a.size() - 2; i++) {
    if (a.get(i).equals("") && a.get(i + 1).equals("Line c") && a.get(i + 2).equals("Line d")) {
        a.remove(i);
        a.remove(i); // has everybody has move forward once, "Line c" if one forward too
        a.remove(i); // same
    }
}

System.out.println(a);
// [Some text, Some more text, , Line a, Line b, Line a, Line b]

条件也可能是

if (a.subList(i, i + 3).equals(List.of("", "Line c", "Line d")))

相关问题