通用字符串处理(1.0 version)

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import java.util.*;
import java.util.function.Consumer;

public class GeneralStringProcessingUtil {

    /**
     * 合并两个字符串值(可以存在逗号分隔)
     *
     * @param existingValues   旧字符串值
     * @param replacementValue 新字符串值
     * @return 合并后的字符串,如果结果为空则返回null
     */
    public static String mergeValues(String existingValues, String replacementValue) {
        // 快速返回:两个都为null, 直接返回null
        if (existingValues == null && replacementValue == null) {
            return null;
        }
        // 快速返回:其中一个为null的情况,直接返回另一个值
        if (existingValues == null) {
            return replacementValue;
        }
        if (replacementValue == null) {
            return existingValues;
        }
        // 使用LinkedHashSet保持插入顺序
        Set<String> valueSet = new LinkedHashSet<>();

        // 添加并分割字符串
        addValuesToSet(valueSet, existingValues);
        addValuesToSet(valueSet, replacementValue);

        return CollectionUtil.isNotEmpty(valueSet) ? String.join(",", valueSet) : null;
    }

    /**
     * 将Map<String, Object>转换为Map<Long, String>
     *
     * @param sourceMap 源Map,key为String类型,value为Object类型
     * @return 转换后的Map,key为Long类型,value为String类型
     */
    public static Map<Long, String> convertToLongStringMap(Map<String, Object> sourceMap) {
        // 1. 空值检查:如果源Map为null,返回空Map避免NullPointerException
        if (sourceMap == null) {
            return Collections.emptyMap(); // 返回不可变的空Map
        }

        // 2. 返回结果
        return sourceMap.entrySet().stream()
                // 2.1 过滤掉key或value为null的条目,避免后续处理出现NullPointerException
                .filter(entry -> entry.getKey() != null && entry.getValue() != null)
                // 2.2 使用collect方法进行收集,三个参数分别对应:
                //     - supplier: 提供新的HashMap实例
                //     - accumulator: 如何将每个元素添加到结果容器中
                //     - combiner: 如何合并两个结果容器(用于并行流)
                .collect(
                        // supplier: 创建结果容器
                        HashMap::new,
                        // accumulator: 累加器,处理每个元素
                        (map, entry) -> {
                            try {
                                // 将String类型的key转换为Long
                                Long longKey = Long.parseLong(entry.getKey());
                                // 将Object类型的value转换为String
                                // 使用toString()而不是强制转换,因为value可能是各种类型
                                String stringValue = entry.getValue().toString();
                                // 将转换后的key-value放入结果Map
                                map.put(longKey, stringValue);
                            } catch (NumberFormatException e) {
                                // 当key无法转换为Long类型时捕获异常
                                // 可以选择记录日志,或者忽略这个条目
                                // 例如: log.warn("无法转换key为Long类型: {}", entry.getKey());

                                // 这里直接忽略无法转换的key,不添加到结果Map中
                                // 可以根据实际需求决定是否需要抛出异常 抛出时可用该方法的重载方法
                            }
                        },
                        // combiner: 合并器,用于并行流中合并多个结果Map
                        (map1, map2) -> {
                            // 将map2中的所有条目添加到map1中
                            // 如果有重复的key,map2的值会覆盖map1的值
                            map1.putAll(map2);
                        }
                );
    }

    /**
     * 重载方法:允许自定义异常处理逻辑
     *
     * @param sourceMap 源Map
     * @param exceptionHandler 异常处理器,用于自定义处理NumberFormatException
     * @return 转换后的Map
     */
    public static Map<Long, String> convertToLongStringMap(
            Map<String, Object> sourceMap,
            Consumer<Map.Entry<String, Object>> exceptionHandler) {

        if (sourceMap == null) {
            return Collections.emptyMap();
        }

        return sourceMap.entrySet().stream()
                .filter(entry -> entry.getKey() != null && entry.getValue() != null)
                .collect(
                        HashMap::new,
                        (map, entry) -> {
                            try {
                                map.put(Long.parseLong(entry.getKey()), entry.getValue().toString());
                            } catch (NumberFormatException e) {
                                // 使用自定义的异常处理器处理转换失败的条目
                                exceptionHandler.accept(entry);
                            }
                        },
                        HashMap::putAll
                );
    }

/** =========================================  辅助方法  ==============================================================
    /**
     * 将逗号分隔的字符串值添加到集合中
     */
    private static void addValuesToSet(Set<String> set, String values) {
        if (StringUtils.isBlank(values)) {
            return;
        }

        String[] splitValues = values.split(",");
        for (String value : splitValues) {
            String trimmed = value.trim(); // 去除空格
            if (StringUtils.isNotBlank(trimmed)) {
                set.add(trimmed);
            }
        }
    }


}

 

posted @ 2026-05-27 15:26  岁月记忆  阅读(16)  评论(0)    收藏  举报