[英]Java: split a list of Dates in sublists that rappresent ranges of days from original lists
[英]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.