Dart list intersection

I am properly misunderstanding your problem but it seems you can achieve the same output by doing this:

void performUnSubscribe[String e] => print['Unsubscribe from $e']; void performSubscribe[String e] => print['Subscribe to $e']; void main[] { final topics = [ ['X311', 'Y739', 'C0', 'V1', 'x43', 'y5', 'D3179'], //currently subscribed list of topics ['X319', 'Y732', 'C0', 'V1', 'x43', 'y5', 'D3183'] //new list of topics to be subscribed to ]; topics[0] .where[[element] => !topics[1].contains[element]] .forEach[performUnSubscribe]; topics[1] .where[[element] => !topics[0].contains[element]] .forEach[performSubscribe]; }

If your lists are containing a lot of elements, it can be more efficient to use a Set like you are already doing. So it would look like this:

void performUnSubscribe[String e] => print['Unsubscribe from $e']; void performSubscribe[String e] => print['Subscribe to $e']; void main[] { final topics = [ ['X311', 'Y739', 'C0', 'V1', 'x43', 'y5', 'D3179'], //currently subscribed list of topics ['X319', 'Y732', 'C0', 'V1', 'x43', 'y5', 'D3183'] //new list of topics to be subscribed to ]; var set = topics[1].toSet[]; topics[0] .where[[element] => !set.contains[element]] .forEach[performUnSubscribe]; set = topics[0].toSet[]; topics[1] .where[[element] => !topics[0].contains[element]] .forEach[performSubscribe]; }

Or put the logic inside its own method like this:

void performUnSubscribe[String e] => print['Unsubscribe from $e']; void performSubscribe[String e] => print['Subscribe to $e']; void main[] { final topics = [ ['X311', 'Y739', 'C0', 'V1', 'x43', 'y5', 'D3179'], //currently subscribed list of topics ['X319', 'Y732', 'C0', 'V1', 'x43', 'y5', 'D3183'] //new list of topics to be subscribed to ]; runFunctionOnDifference[topics[0], topics[1], performUnSubscribe]; runFunctionOnDifference[topics[1], topics[0], performSubscribe]; } /// Execute [function] on elements in [list1] which are not on [list2]. void runFunctionOnDifference[ List list1, List list2, void Function[T] function] { final set = list2.toSet[]; list1.where[[element] => !set.contains[element]].forEach[function]; }

All three solutions gives:

Unsubscribe from X311 Unsubscribe from Y739 Unsubscribe from D3179 Subscribe to X319 Subscribe to Y732 Subscribe to D3183

Video liên quan

Chủ Đề