在Dart(Flutter)中如何从List<Map<String,Object>>筛选匹配国家名称的元素
实现国家名称的前缀匹配筛选
Dart 实现
直接通过集合的where方法过滤后转成列表即可,推荐做不区分大小写的匹配来提升用户体验:
List<Map<String, Object>> allCountries = [/* 你的原始国家列表 */]; String query = "Af"; // 替换为实际查询字符串 // 筛选名称以查询字符串开头的国家(不区分大小写) List<Map<String, Object>> resultOfQuery = allCountries .where((country) { String countryName = country["name"] as String; return countryName.toLowerCase().startsWith(query.toLowerCase()); }) .toList();
如果需要严格区分大小写,去掉两处toLowerCase()即可。
Java 实现
利用Stream API可以简洁完成筛选:
import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class CountryFilter { public static void main(String[] args) { List<Map<String, Object>> allCountries = /* 你的原始国家列表 */; String query = "Af"; // 替换为实际查询字符串 // 筛选名称以查询字符串开头的国家(不区分大小写) List<Map<String, Object>> resultOfQuery = allCountries.stream() .filter(country -> { String countryName = (String) country.get("name"); return countryName.toLowerCase().startsWith(query.toLowerCase()); }) .collect(Collectors.toList()); } }
额外:精确匹配逻辑
如果需要筛选名称完全匹配查询字符串的国家,只需把判断条件里的startsWith替换为equalsIgnoreCase(不区分大小写)或equals(严格区分大小写)即可。
内容的提问来源于stack exchange,提问作者Alpha diallo
相关产品推荐
相关产品推荐

