如何比较dart中的两个地图



我有两个地图相同的数据(键,值),但我不能比较他们,因为他们不相等?我已经尝试了这个问题的所有答案,但除了我必须将映射更改为字符串(我知道这不是正确的事情)之外,他们都没有给出真实的答案。那么,为什么它们是不相等的,什么是比较它们的正确方法呢?

Map map1 = {28: 67, 33: 60};
Map attributesIndex = {118: {28: 66, 33: 58}, 120: {28: 66, 33: 59}, 121: {28: 66, 33: 60}, 122: {28: 66, 33: 61}, 126: {28: 66, 33: 65}, 127: {28: 67, 33: 59}, 128: {28: 67, 33: 60}, 130: {28: 67, 33: 62}};

测试如下:

import 'package:collection/collection.dart';
attributesIndex.entries.forEach((element) {
if(DeepCollectionEquality().equals(element.value, map1)) {
print('Maps are equal');
} else {
print('Maps are not equal');
}
})

返回false。

import 'package:collection/equality.dart';
attributesIndex.entries.forEach((element) {
if(MapEquality().equals(element.value, map1)){
print('Maps are equal');
} else {
print('Maps are not equal');
}
})

返回false;

attributesIndex.entries.forEach((element) {
if(mapEquals(element.value, map1)){
print('Maps are equal');
}else{
print('Maps are not equal');
}
})

返回false

attributesIndex.entries.forEach((element) {
if(element.value.toString() == map1.toString()){
print('Maps are equal');
} else{
print('Maps are not equal');
}
})

返回true,但我认为这不是正确的方式

第一个代码片段可以工作。如下图所示。

  1. 所有的导入都应该在顶部
  2. 你有语法错误。

对于第二个,相等。达特贬值了。试着更新你的环境。

import 'package:collection/collection.dart';
Map map1 = {28: 67, 33: 60};
Map map2 = {28: 67, 33: 60};

if (DeepCollectionEquality().equals(map1, map2)) {
print('Maps are equal');
} else {
print('Maps are not equal');
}

最新更新