I have two lists, lst1
and lst2
. I want to perform lst1 - lst2
, which returns all elements of lst1
not in lst2
.
var lst1 = ["t1" , "t2" , "t3" , "t4"];
var lst2 = ["t2" , "t4" , "t5"];
//output: ["t1" , "t3"]
The following functions supported by the List class in the dart:core library can be used to remove the item (s) in a List. The List.remove () function removes the first occurrence of the specified item in the list.
The List.remove () function removes the first occurrence of the specified item in the list. This function returns true if the specified value is removed from the list. value − represents the value of the item that should be removed from the list.
The List.removeLast () function pops and returns the last item in the List. The syntax for the same is as given below − The List.removeRange () function removes the items within the specified range.
If you want to remove a list of objects ( list2) from another list ( list1) use: Remember to use ToList () to convert IEnumerable<T> to List<T>. Show activity on this post. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share your research! But avoid …
Convert to sets and take the difference, then convert back to a list (with the caveat that neither duplicates nor the ordering of elements will be preserved):
void main() {
var lst1 = ["t1" , "t2" , "t3" , "t4"];
var lst2 = ["t2" , "t4" , "t5"];
var set1 = Set.from(lst1);
var set2 = Set.from(lst2);
print(List.from(set1.difference(set2)));
}
Output
[t1, t3]
Try it online
The method using sets suggested by Ray Toal is probably the fastest, but if your first list contains duplicates that you want to keep, sets will completely destroy them.
Instead, you could use a simple list filtering method.
void main() {
var lst1 = ["t1" , "t2" , "t2", "t3" , "t3", "t4"]; // introduce duplicates
var lst2 = ["t2" , "t4" , "t5"];
var set1 = Set.from(lst1);
var set2 = Set.from(lst2);
print(List.from(set1.difference(set2)));
// Output : [t1, t3]
var filtered_lst = List.from(lst1.where(
(value) => !lst2.contains(value)));
print(filtered_lst);
// Output: [t1, t3, t3]
}
If there is duplicates in both lists and you actually want to subtract list item per item, you could use the remove
method (warning: this will actually remove items from your first list, so you might need to create a copy first).
void main() {
var lst1 = ["t1" , "t2" , "t2", "t3" , "t3", "t4"]; // introduce duplicates
var lst2 = ["t2" , "t4" , "t5"];
for (var elem in lst2) {
lst1.remove(elem);
}
print(lst1);
// Output : [t1, t2, t3, t3]
// only one occurrence of "t2" was removed.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With