'Java - How to check if a list is in list of lists [closed]
I have a list and list of lists.
How do I check if data is in sheet list and remove it from data list? I tried using containsAll() but it's not removing the same list. I might be doing something wrong.
import java.util.*;
public class RemoveSameListData {
public static void main(String[] args) {
List<List<Object>> sheet = new ArrayList<>();
List<Object> data = new ArrayList<>();
data.add("a");
data.add("a");
data.add("b");
List<Object> data2 = new ArrayList<>();
data2.add("c");
data2.add("b");
data2.add("bv");
List<Object> data3 = new ArrayList<>();
data3.add("s");
data3.add("as");
data3.add("e");
sheet.add(data);
sheet.add(data2);
sheet.add(data3); //here sheet is [[a, a, b], [c, b, bv], [s, as, e]]
for (List<Object> sameData : sheet) {
if(data.containsAll(sameData)) {
data.remove(sameData);
}
}
System.out.println(data);
}
}
Basically, i want to be able to remove list from data that's available in sheet.
Any input is always appreciated. Thank you
Solution 1:[1]
like @Lei Yang pointed out in his comment (credits to him!), the equality of list's is checked by equality of the objects.
Thus this succeeds:
List<List<Object>> sheet = new ArrayList<>(List.of(List.of("a", "a", "b"), List.of("c", "b", "bv"), List.of("s", "as", "e")));
List<Object> data = List.of("a", "a", "b");
assertTrue(sheet.remove(data));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | RainerZufall |
