Home > OS >  Any Dart List Method that works this way?
Any Dart List Method that works this way?

Time:06-17

class Word{
String word;
Word({required this.word});
}
List<Word> firstList = ["Add","All","Human","Moon","Free"];
List<Word> secondList= ["Add","Human","Free"];

If the element in the first list exists in the second list, I want it to return true, otherwise false.

Output that should be:

true
false
true
false
true

CodePudding user response:

First, I'd make sure that Word can be compared easily:

class Word {
  String word;
  Word({required this.word});

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;

    return other is Word && other.word == word;
  }

  @override
  int get hashCode => word.hashCode;
}

Then you can do:

print(firstList.map((w) => secondList.contains(w)));

Check this DartPad for it

  • Related