You need to enable JavaScript to run this app. Flutter Dart如何从City对象列表提取name属性生成字符串列表
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Dart如何从City对象列表提取name属性生成字符串列表

从List<City>提取所有name属性生成List<String>的实现方案

以下是不同主流开发语言的常用实现方式:

Java(JDK8+)

使用Stream API可以快速实现:

// JDK8 ~ JDK15 版本
import java.util.stream.Collectors;

List<String> names = cities.stream()
    .map(City::getName)
    .collect(Collectors.toList());

// JDK16及以上版本可以简化写法
List<String> names = cities.stream().map(City::getName).toList();

如果是低版本JDK,用普通遍历实现:

List<String> names = new ArrayList<>();
for (City city : cities) {
    names.add(city.getName());
}

注意:Java场景下需要确保City类为name属性提供了public的getName() getter方法,否则会出现编译错误。


Dart

List<String> names = cities.map((city) => city.name).toList();

Kotlin

Kotlin支持自动类型推导,写法非常简洁:

val names = cities.map { it.name }

Python

用列表推导式即可快速完成转换:

names = [city.name for city in cities]

内容的提问来源于stack exchange,提问作者Mohammed Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 06:15:03