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

如何基于字符位置Map排序并重建含空格的原字符串?

问题背景

我正在学习Collections和Stream技术,已经把句子**"Hello Word!"**拆分并记录了每个非空格字符的位置,代码实现如下:

实现代码

private static final String text = "Hello Word!";
static Map<String, List<Integer>> charsIndex = new HashMap<>();
static void charsIndex() {

        List<Character> charsList = text
                .chars()
                .mapToObj(e -> (char) e)
                .toList();
        System.out.println(charsList);

        int  position = 0;
        for (Character c : charsList) {
            if(!c.toString().isBlank()){
                charsIndex.computeIfAbsent(c.toString(),
                        addCharPosition -> new ArrayList<>()).add(position);
            }
            position += 1;
        }

        System.out.println(charsIndex);
}

运行结果

[H, e, l, l, o, , W, o, r, d, !] (charsList)

{!=[10], r=[8], d=[9], e=[1], W=[6], H=[0], l=[2, 3], o=[4, 7]} (charsIndex)

现在我想对字符按位置排序,重建包含空格的原字符串,尝试了下面的代码但还没完成:

static void charsToString(){

  charsIndex.forEach((character, l) -> l.forEach(position -> {

  }));
}

解决方案

要重建原字符串,核心是按位置索引从0到最大位置依次填充字符,直接给出两种可行实现:

基础数组填充实现

这种方式直观易懂,完美还原原字符串的空格位置:

static void charsToString(){
    // 获取原字符串的总长度:找到所有记录的位置最大值加1
    int maxPosition = charsIndex.values().stream()
            .flatMap(List::stream)
            .max(Integer::compare)
            .orElse(-1) + 1;
    // 初始化全空格的字符数组,对应原字符串的空格位置
    char[] resultArr = new char[maxPosition];
    Arrays.fill(resultArr, ' ');

    // 遍历每个字符和对应的位置列表,填充到数组对应索引
    charsIndex.forEach((charStr, positions) -> {
        char c = charStr.charAt(0);
        positions.forEach(pos -> resultArr[pos] = c);
    });

    // 转成字符串并输出
    String result = new String(resultArr);
    System.out.println(result); // 输出:Hello Word!
}

Stream风格实现

如果想用Stream简化逻辑,同时保证通用性:

static void charsToStringWithStream(){
    // 先确定原字符串总长度
    int totalLength = charsIndex.values().stream()
            .flatMapToInt(list -> list.stream().mapToInt(Integer::intValue))
            .max().orElse(-1) + 1;
    // 创建全空格的StringBuilder
    StringBuilder sb = new StringBuilder(" ".repeat(totalLength));
    
    // 遍历字符和位置,替换对应位置的字符
    charsIndex.forEach((charStr, positions) -> {
        char c = charStr.charAt(0);
        positions.forEach(pos -> sb.setCharAt(pos, c));
    });
    
    String result = sb.toString();
    System.out.println(result); // 输出:Hello Word!
}

关键说明

  • 两种实现都先处理了原字符串的空格:因为空格没被记录在charsIndex中,所以初始化时用空格填充所有位置,再覆盖非空格字符的位置
  • 无需额外排序,直接按位置填充即可还原原字符串的顺序

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:25:26