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

Java 8如何通过Stream分割List<String>提取前缀数字至新列表

Java 8 Stream提取"-"前数字的实现

直接上可运行的代码:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<String> deptList = Arrays.asList("12-dept20", "13-dept50");
        
        List<Integer> numList = deptList.stream()
                // 分割字符串,取"-"前的部分并转为Integer
                .map(s -> Integer.parseInt(s.split("-")[0]))
                // 收集为Integer类型的List
                .collect(Collectors.toList());
        
        System.out.println(numList); // 输出 [12, 13]
    }
}

关键步骤说明:

  • 转流:调用stream()方法将原List<String>转为Stream流,开启流式操作。
  • 映射转换:使用map()方法对每个字符串做处理:
    1. 用split("-")把字符串按"-"分割成数组,比如"12-dept20"会分成["12", "dept20"];
    2. 取数组索引为0的元素(即"-"前的数字字符串);
    3. 用Integer.parseInt()将字符串转为Integer类型。
  • 收集结果:调用collect(Collectors.toList())把处理后的流元素收集成List<Integer>。

额外提示(处理异常情况)

如果原集合中存在不符合{数字}-{其他内容}格式的字符串,会抛出NumberFormatException或ArrayIndexOutOfBoundsException。可以加个过滤和异常处理来增强鲁棒性:

List<Integer> numList = deptList.stream()
        .filter(s -> s.contains("-")) // 先过滤掉不含"-"的元素
        .map(s -> {
            try {
                return Integer.parseInt(s.split("-")[0]);
            } catch (NumberFormatException e) {
                // 处理数字格式错误的情况,比如返回null或跳过
                return null;
            }
        })
        .filter(num -> num != null) // 过滤掉转换失败的null值
        .collect(Collectors.toList());

内容的提问来源于stack exchange,提问作者neha menezes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 12:52:07