我有列表列表的结构,如果列表包含在另一个列表中,我想删除它。
例如,我有一个列表列表,如下所示:
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内置方法或可以删除子列表的方法。
由于
答案 0 :(得分:2)
您可以使用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)
。
答案 1 :(得分:2)
我不认为有一种内置方法可以完全按照您的意愿行事,但使用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]
您可以根据您的条件存储列表的索引,然后将其删除