You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何对List<String>进行升序排序?

实现字符串列表按前缀数字升序排序

当然可以实现,核心思路是提取每个字符串开头的数字部分,以此作为排序依据。以下是Java语言的具体实现代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ListSortExample {
    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();
        myList.add("2. Grammar");
        myList.add("3. Pronunciation");
        myList.add("1. Verbs");

        // 自定义比较器,提取前缀数字进行排序
        Collections.sort(myList, new Comparator<String>() {
            @Override
            public int compare(String s1, String s2) {
                // 提取字符串中的数字部分
                int num1 = Integer.parseInt(s1.split("\\.")[0].trim());
                int num2 = Integer.parseInt(s2.split("\\.")[0].trim());
                return Integer.compare(num1, num2);
            }
        });

        // 输出排序后的列表
        System.out.println(myList); // 输出:[1. Verbs, 2. Grammar, 3. Pronunciation]
    }
}

如果使用Java 8及以上版本,还可以用Lambda表达式简化比较器代码:

Collections.sort(myList, (s1, s2) -> {
    int num1 = Integer.parseInt(s1.split("\\.")[0].trim());
    int num2 = Integer.parseInt(s2.split("\\.")[0].trim());
    return Integer.compare(num1, num2);
});

注意事项

  • 确保列表中每个字符串都以数字.的格式开头,否则split或parseInt方法会抛出异常,实际生产环境中建议添加异常捕获逻辑,避免程序崩溃。
  • 该逻辑支持多位数前缀(比如10. Vocabulary),Integer.parseInt可以正确解析多位数数字。

内容的提问来源于stack exchange,提问作者Sanjay Tandukar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 12:06:45