簡體   English   中英

有沒有辦法從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<List<>> ,您可以使用List::containsAll

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()實現起來並不困難:

使用您在此處提供的值是一個快速示例,以說明如何識別子/相等列表:

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] 

您可以根據您的條件存儲列表的索引,然后將其刪除

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM