可以使用 Guava 的 Splitter 和 Maps 工具类来实现。

首先,使用 Splitter 按照逗号和竖线进行分割,将字符串拆分成键值对。然后,使用 Maps.uniqueIndex 方法将拆分后的键值对转换为 Map。

接下来,使用 Map 的 get 方法获取指定键对应的值,并使用 Guava 的 Strings 类 的 nullToEmpty 方法将空值转换为空字符串。最后,使用 Integer.parseInt 方法将字符串转换为整数。

以下是示例代码:

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String input = '100001|30,100002|45';
        String key = '100005';

        Map<String, String> map = Splitter.on(',')
                .withKeyValueSeparator('|')
                .split(input);

        String value = Strings.nullToEmpty(map.get(key));
        int result = Integer.parseInt(value);

        System.out.println(result);
    }
}

输出结果为 0,表示没有找到对应的值。如果要避免出现空指针异常,可以使用 Strings.nullToEmpty 方法将 null 值转换为空字符串,然后再使用 Integer.parseInt 方法将字符串转换为整数。


原文地址: https://www.cveoy.top/t/topic/pkLS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录