简体   繁体   中英

How to get unique object from two List<Map>?

I have two lists which is map type. How can I get unique objects from both arrays?

List<Map> arr = [ {"id": "1", "name": "Apple"}, {"id": "2", "name": "Banana"}, {"id": "3", "name": "Cake"}, {"id": "4", "name": "Dog"} ]; 
List<Map> arr1 = [ {"id": "1", "name": "Apple"}, {"id": "2", "name": "Boy"}, {"id": "3", "name": "Cow"}, {"id": "4", "name": "Dog"} ]; 

output should be like this :

List<Map> arr3 = [ {"id": "2", "name": "Banana"}, {"id": "3", "name": "Cake"}, {"id": "2", "name": "Boy"}, {"id": "3", "name": "Cow"} ];

You could use this :

List<Map> getUniq(List<Map> arr1, List<Map> arr2) {
  List<Map> res = [];
  for (var el1 in arr1)
    for (var el2 in arr2)
      if (el1['id'] == el2['id'] && el1['name'] != el2['name'])
        res.addAll([el1, el2]);
  return res;
}

In you case :

List<Map> arr3 = getUniq(arr, arr1);
// outputs [{id: 2, name: Banana}, {id: 2, name: Boy}, {id: 3, name: Cake}, {id: 3, name: Cow}]

As you can see it returns only items with same id but different name .

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