Home > OS >  How do I check if two HashMaps are equal in Dart?
How do I check if two HashMaps are equal in Dart?

Time:06-02

The default behavior for all Objects in Dart is to return true if and only if this object and other are the same object. How do I check if the values are the same?

import 'dart:collection' show HashMap;

final Map<int, String> planets1 = HashMap(); // Is a HashMap
final Map<int, String> planets2 = HashMap(); // Is another HashMap
planets1.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
planets2.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
print(planets1 == planets2); // prints false

CodePudding user response:

Try this

print(planets1.toString() === planets2.toString()); // prints true

CodePudding user response:

First import this package:

import 'package:collection/equality.dart';

and then print it out:

print(MapEquality().equals(planets1, planets1));

CodePudding user response:

import 'dart:collection';

import 'package:quiver/collection.dart';

void main() {
  final Map<int, String> planets1 = HashMap(); // Is a HashMap
  final Map<int, String> planets2 = HashMap(); // Is another HashMap
  planets1.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
  planets2.addAll({5: 'Saturn', 6: 'Jupiter', 3: 'Earth', 4: 'Mars'});
  print(mapsEqual(planets1, planets2)); // prints true
}

  •  Tags:  
  • dart
  • Related