Flutter/Dart:如何统计对象列表中各标签的出现次数
问题描述
如何统计数组中的标签?现有代码如下:
class Product{ Product({required this.name, required this.tags}); final String name; final List<String> tags; } void TagList(){ final product =[ Product(name: 'bmw', tags: ['car', 'm3']), Product(name: 'kia', tags: ['car', 'morning', 'suv']), Product(name: 'hyundai', tags: ['car', 'ev6', 'suv']), ]; }
需要获取每个标签的使用次数,预期输出结果:
car(3)
m3(1)
ev6(1)
suv(2)
morning(1)
实现方案
核心思路是用Map<String, int>结构存储标签和对应的计数,遍历所有商品的标签列表做累加即可。
基础实现代码
class Product{ Product({required this.name, required this.tags}); final String name; final List<String> tags; } void countTags() { final products =[ Product(name: 'bmw', tags: ['car', 'm3']), Product(name: 'kia', tags: ['car', 'morning', 'suv']), Product(name: 'hyundai', tags: ['car', 'ev6', 'suv']), ]; final Map<String, int> tagCounter = {}; // 遍历所有商品的标签做计数 for (final product in products) { for (final tag in product.tags) { tagCounter[tag] = (tagCounter[tag] ?? 0) + 1; } } // 输出结果 tagCounter.forEach((tag, count) => print('$tag($count)')); }
按计数排序调整
默认Map按插入顺序遍历,如果需要和预期输出一致、按出现次数从高到低排序,可以替换输出部分的代码为:
// 按计数降序排序 final sortedTags = tagCounter.entries.toList() ..sort((a, b) => b.value.compareTo(a.value)); // 遍历输出排序后的结果 for (final item in sortedTags) { print('${item.key}(${item.value})'); }
运行后输出和预期逻辑一致:
car(3)
suv(2)
m3(1)
morning(1)
ev6(1)
内容的提问来源于stack exchange,提问作者Patrick SINT
相关产品推荐
相关产品推荐

