Zarif Muhtasim
Zarif Muhtasim

Reputation: 334

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

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

Upvotes: 2

Views: 120

Answers (3)

mezoni
mezoni

Reputation: 11220

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
}

Upvotes: 0

Baskman
Baskman

Reputation: 105

First import this package:

import 'package:collection/equality.dart';

and then print it out:

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

Upvotes: 1

Zarif Muhtasim
Zarif Muhtasim

Reputation: 334

Try this

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

Upvotes: 0

Related Questions