Home > Net >  Get the sum of numbers for similar element in a list of object in Dart?
Get the sum of numbers for similar element in a list of object in Dart?

Time:10-05

I need to iterate over a list of object and sum all "num" for every "title"

var obj1 = MyObject(tNum: 10, tTitle: 'Hi');
var obj2 = MyObject(tNum: 9, tTitle: 'Hi');
var obj3 = MyObject(tNum: 8, tTitle: 'Hello');
var obj4 = MyObject(tNum: 7, tTitle: 'Hello');
var obj5 = MyObject(tNum: 12, tTitle: 'Good');
var myList = [obj1, obj2, obj3, obj4, obj5];



var myListIter = myList.iterator;
  var initialTitle = '';
  var finalSum = 0;

  while (myListIter.moveNext()) {
    print(myListIter.current);
    if (myListIter.current.title!.compareTo(initialTitle).isEven) {
      finalSum = finalSum   myListIter.current.num!;
    }else{
      print('--- ${myListIter.current.title!} : $finalSum');
    }
  }
}

class MyObject {
  int? num;
  String? title;
  MyObject({tNum, tTitle}) {
    num = tNum;
    title = tTitle;
  }
}

The output:

--- Hi : 0
--- Hi : 0
--- Hello : 0
--- Hello : 0
--- Good : 0

Expected output:

--- Hi : 19
--- Hello : 15
--- Good : 12

What is the simplest way to do that? q,nfczej,pvledv;lzecaz

CodePudding user response:

  var myMap = <String, int>{};
  myList.forEach((obj) => myMap[obj.title!] = (myMap[obj.title] ?? 0)   obj.num!);
  print(myMap);

Output:

{Hi: 19, Hello: 15, Good: 12}
  •  Tags:  
  • dart
  • Related