总和值并删除列表中的重复项

时间:2019-11-10 10:42:23

标签: flutter dart

我有此列表,想对值求和并删除列表中的重复项

1-检查productName

2-如果productName等于,则将NumberOfItems相加

例如:

"Orders":[
    {
        "productName":"Apple",
        "NumberOfItems":"5"
    },
    {
        "productName":"Orange",
        "NumberOfItems":"2"
    },
    {
        "productName":"Egg",
        "NumberOfItems":"5"
    },
    {
        "productName":"Apple",
        "NumberOfItems":"3"
    },
    {
        "productName":"Orange",
        "NumberOfItems":"4"
    },
    {
        "productName":"Egg",
        "NumberOfItems":"9"
    },
]

我需要的结果如下所示:(总和取决于productName)

"Orders":[
    {
        "productName":"Apple",
        "NumberOfItems":"8"
    },
    {
        "productName":"Orange",
        "NumberOfItems":"6"
    },
    {
        "productName":"Egg",
        "NumberOfItems":"14"
    },
]

3 个答案:

答案 0 :(得分:1)

final orders = data["Orders"] as List;
final mapped = orders.fold<Map<String, Map<String, dynamic>>>({}, (p, v) {
  final name = v["productName"];

  if (p.containsKey(name)) {
    p[name]["NumberOfItems"] += int.parse(v["NumberOfItems"]);
  } else {
    p[name] = {
      ...v,
      "NumberOfItems": int.parse(v["NumberOfItems"])
    };
  }

  return p;
});

final newData = {
  ...data,
  "Orders": mapped.values,
};

print(newData);

结果是:

  

{订单:({productname:Apple,NumberOfItems:8},{productName:Orange,NumberOfItems:6},{productName:Egg,NumberOfItems:14})}

答案 1 :(得分:1)

注意:此代码有2个循环,表示速度较慢。 伊戈尔·克拉霍霍尔丁(Igor Kharakhordin)回答的比较聪明,但是对于那些问这个问题的人来说可能很难。(因为他一次要做两件事。)基本上我是在做同一件事。

String string = await rootBundle.loadString("asset/data/Orders.json");
  Map orders = jsonDecode(string);
  List orderList = orders["Orders"];

  Map<String,int> sums = {};

  for(int i = 0 ; i < orderList.length; i++){
    dynamic item = orderList[i];
    if(sums.containsKey(item["productName"])){
      sums[item["productName"]] += int.parse(item["NumberOfItems"]);
    }
    else{
      sums[item["productName"]] = int.parse(item["NumberOfItems"]);
    }
  }

  List sumList = [];
  sums.forEach((key,value)=> 
      sumList.add({
      "productName":key,
      "NumberOfItems":value.toString()
    })
  );

  Map result = {
    "Orders":sumList
  };

  print(jsonEncode(result));

结果

{
    "Orders": [
        {
            "productName": "Apple",
            "NumberOfItems": "8"
        },
        {
            "productName": "Orange",
            "NumberOfItems": "6"
        },
        {
            "productName": "Egg",
            "NumberOfItems": "14"
        }
    ]
}

答案 2 :(得分:0)

private static class GetContacts extends AsyncTask<String, Void, String> { ProgressDialog dialog; ArrayList<Actors> actors = new ArrayList<>(); ... @Override protected String doInBackground(String... sText1) { ... for (int i = 0; i < actors.length(); i++) { ... // activityReference.get().actorsList.add(actor); <-- remove this. actors.add(actor); } ... } protected void onPostExecute(String result) { super.onPostExecute(result); Zoznam activity = activityReference.get(); if (activity == null || activity.isFinishing()) return; dialog.dismiss(); activityReference.get().actorsList.add(actors); <-- add this activity.adapter.notifyDataSetChanged(); } } 方法允许您通过指定的分组键对序列值进行分组。根据您的情况,可以从groupBy的值获取此密钥。
输入序列将被延迟转换为新序列,其中每个组均可使用该键。
然后,您可以选择此新序列(使用productName方法)并生成所需的结果。
同时,在形成结果时,您可以变换每个分组的元素(或对它们进行任何计算,例如,对分组元素的值求和)。

select

结果:

{Orders: [{productName: Apple, NumberOfItems: 8}, {productName: Orange, NumberOfItems: 6}, {productName: Egg, NumberOfItems: 14}]}

另一个更复杂的示例(同时实现起来也并不困难):

import 'package:enumerable/enumerable.dart';

void main(List<String> args) {
  final q = orders['Orders'].groupBy((e) => e['productName']).select((g) => {
        'productName': g.key,
        'NumberOfItems': g.sum$1((e) => int.parse(e['NumberOfItems']))
      });
  print({'Orders': q.toList()});
}

final orders = {
  "Orders": [
    {"productName": "Apple", "NumberOfItems": "5"},
    {"productName": "Orange", "NumberOfItems": "2"},
    {"productName": "Egg", "NumberOfItems": "5"},
    {"productName": "Apple", "NumberOfItems": "3"},
    {"productName": "Orange", "NumberOfItems": "4"},
    {"productName": "Egg", "NumberOfItems": "9"},
  ]
};
{Orders: [{productName: Apple, NumberOfItems: 8, Amount: 77.25}, {productName: Orange, NumberOfItems: 6, Amount: 45.8}, {productName: Egg, NumberOfItems: 14, Amount: 46.55}]}