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

如何使用Stream遍历内部类元素并提取sourceKey末尾数字

问题描述

我有如下类层级结构,想要提取并打印所有sourceKey字段中的末尾数字(比如示例里的22、44)。我尝试了一段不完整的代码:

System.out.println(person.prsndtl.items.stream().map(PrsnDtl.Item::toString));

sourceKey的示例值如下:

AAA:C:22
BBB:C:44

请问如何遍历所有items并实现这个需求?类结构代码如下:

@Getter
@Setter
@ToString
public class Person {

    @JsonProperty("MyPrsnDtl")
    public PrsnDtl prsndtl;

}

@Getter
@Setter
@ToString
public class PrsnDtl {

    @JsonProperty("item")
    @Getter
    @Setter
    public List<Item> items = new ArrayList<>();

    @Getter
    @Setter
    @ToString
    public static final class Item {

        @JsonProperty("key")
        public Key key;
    }
}

@Getter
@Setter
@ToString
public class Key {
    @JsonProperty("sourceKey")
    public String sourceKey;
}
解决方案

要实现需求,你需要通过Stream API逐层访问到sourceKey,再提取末尾数字,具体实现如下:

方法1:按冒号分割提取(适用于固定格式的sourceKey)

如果sourceKey的格式固定为XXX:XXX:数字,可以直接通过分割字符串取最后一段:

person.prsndtl.getItems().stream()
    // 过滤key不为空的Item
    .filter(item -> item.getKey() != null)
    .map(item -> item.getKey().getSourceKey())
    // 过滤sourceKey不为空且包含冒号的情况
    .filter(sourceKey -> sourceKey != null && sourceKey.contains(":"))
    .map(sourceKey -> {
        String[] parts = sourceKey.split(":");
        return parts[parts.length - 1];
    })
    .forEach(System.out::println);

方法2:正则表达式匹配(适用于格式不固定但末尾是数字的情况)

如果sourceKey的格式不固定,但末尾一定是数字,用正则匹配更严谨:

import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 定义匹配末尾连续数字的正则
Pattern numPattern = Pattern.compile("\\d+$");

person.prsndtl.getItems().stream()
    // 过滤空值,避免空指针
    .filter(item -> item.getKey() != null && item.getKey().getSourceKey() != null)
    .map(item -> item.getKey().getSourceKey())
    .map(sourceKey -> {
        Matcher matcher = numPattern.matcher(sourceKey);
        return matcher.find() ? matcher.group() : null;
    })
    // 过滤匹配失败的结果
    .filter(Objects::nonNull)
    .forEach(System.out::println);

关键说明

  • 加入filter步骤是为了避免NullPointerException,比如某个Item的key为null,或者sourceKey为空、格式不符合的情况。
  • 两种方法可根据实际的sourceKey格式选择:固定冒号分隔用分割法更高效;格式多变但末尾是数字用正则更可靠。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 09:52:27