有没有办法从 Java 中的列表列表中删除子列表?

Is there a way to remove sublists from a list of lists in Java?

我有列表列表的结构,如果一个列表包含在另一个列表中,我想删除它。

例如,我有如下列表:

listOfLists = { {C1, C2, C3},
                  {C1, C2, C3, C4, C5, C6},
                  {C1, C2, C3, C4, C5, C6, C7} }

因此,{C1, C2, C3}{C1, C2, C3, C4, C5, C6} 应该删除,因为它已经包含在另一个列表 {C1, C2, C3, C4, C5, C6, C7} 中。最后,我新建的listOfLists去掉后就变成了下面给出的例子;

listOfLists = { {C1, C2, C3, C4, C5, C6, C7} }

综上所述,是否有Java内置方法或可以删除​​子列表的方法。

谢谢

您可以使用 List::containsAll,假设您使用的是 List<List<>>

List<List<C>> result = new ArrayList<>();

outerloop:
for(List<C> list1 : listOfLists) {
    for(List<C> list2 : listOfLists) {
        if(list1 != list2) {
            if(list2.containsAll(list1)) {
                continue outerloop; // list1 is a sub-list of list2, continue without adding
            }
        }
    }
    result.add(list1); // only adds if list1 is not contained by any other list.
}

请注意,如果您有等效列表,它们都将被删除。如果你不想这样,你应该将参考比较 (list1 != list2) 更改为 !list1.equals(list2).

我认为没有内置方法可以完全按照您的要求执行操作,但是使用 containsAll():

实现起来并不难

使用您在此处提供的值是一个快速示例,用于说明如何识别 sub/equal 列表:

public static void main(String[] args){
     List<Integer> listOne = new ArrayList<>(Arrays.asList(1,2,3));
     List<Integer> listTwo = new ArrayList<>(Arrays.asList(1,2,3,4,5,6));
     List<Integer> listThree = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7));
     List<Integer> listFour = new ArrayList<>(Arrays.asList(1,2,3,4,5,7,6));
     List<List<Integer>> listOfLists = new ArrayList<>(Arrays.asList(listOne, listTwo, listThree, listFour));

        for(int currentIndex = 0; currentIndex < listOfLists.size(); currentIndex++) {
            List<Integer> currentList = listOfLists.get(currentIndex);
            for (int comparisonIndex = 0; comparisonIndex < listOfLists.size(); comparisonIndex++) {
                if(currentIndex == comparisonIndex) { continue; }
                List<Integer> comparisonList = listOfLists.get(comparisonIndex);
                if(comparisonList.containsAll(currentList)){
                    boolean isEqualSet = comparisonList.size() == currentList.size();
                    System.out.println(currentList + " is " + (isEqualSet ? "an equal set of: " : "a subset of: ") + comparisonList);
                    continue;
                }
            }
        }
    }


输出:

[1, 2, 3] is a subset of: [1, 2, 3, 4, 5, 6]
[1, 2, 3] is a subset of: [1, 2, 3, 4, 5, 6, 7]
[1, 2, 3] is a subset of: [1, 2, 3, 4, 5, 7, 6]
[1, 2, 3, 4, 5, 6] is a subset of: [1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6] is a subset of: [1, 2, 3, 4, 5, 7, 6]
[1, 2, 3, 4, 5, 6, 7] is an equal set of: [1, 2, 3, 4, 5, 7, 6]
[1, 2, 3, 4, 5, 7, 6] is an equal set of: [1, 2, 3, 4, 5, 6, 7]

您可以根据您的条件存储列表的索引,然后删除它们