简体   繁体   中英

Dart: 2 lists, show elements of list a that aren't in list b

I'm trying to compare 2 lists. (Dart (flutter))

List a = [1,2,3,4]
List b = [2,3]

I want to find the elements of List a that aren't in List b. Outcome:

List c = [1,4]

Which method should I use? From math at school, I know you can use intersection to find the communal elements, but don't know the name for this 'method'.

Thanks in advance!

This is much easier if you use sets instead of lists: the Set.difference method does exactly this.

Alternatively, if you want the output to be a list (to maintain the ordering from list a ), the most efficient way is still to store the elements from list b in a set, then use a loop over list a to build the list c out of the elements which aren't in set b , using the Set.contains method.

Solution using static extension methods.

import 'package:enumerable/enumerable.dart';

void main(List<String> args) {
  final a = [1, 2, 3, 4];
  final b = [2, 3];
  final q = a.except(b);
  print(q.toList());
}

Result:

[1, 4]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM