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

如何用Java Streams以惯用方式为嵌套列表的每个子列表前置元素?

问题描述

现有基础列表:

[["foo"],["bar"]]

以及输入字符串 "a",需要将该字符串前置到列表中的每个子列表,最终得到结果:

[["a", "foo"], ["a", "bar"]]

对应的JavaScript实现如下:

const base = [["foo"], ["bar"]]
const prefix = "a"
const prefixedBase = base.map(it => [prefix, ...it])

请问如何用Java Streams以类似的惯用格式实现该功能?


Java Streams 实现方案

核心思路和JavaScript的map逻辑一致:遍历原列表的每个子列表,生成包含前缀元素+原子列表元素的新列表,最终收集为结果列表。

基础实现

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

public class PrefixListDemo {
    public static void main(String[] args) {
        List<List<String>> base = List.of(List.of("foo"), List.of("bar"));
        String prefix = "a";

        List<List<String>> prefixedBase = base.stream()
                .map(subList -> {
                    // 创建新列表,先添加前缀,再追加原子列表所有元素
                    List<String> newSubList = new ArrayList<>();
                    newSubList.add(prefix);
                    newSubList.addAll(subList);
                    return newSubList;
                })
                .collect(Collectors.toList());

        System.out.println(prefixedBase); // 输出:[[a, foo], [a, bar]]
    }
}

贴近JS展开运算符的简化写法

可以用Stream.concat()把前缀元素的流和原子列表的流拼接起来,再收集为列表,写法更简洁:

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

public class PrefixListDemo {
    public static void main(String[] args) {
        List<List<String>> base = List.of(List.of("foo"), List.of("bar"));
        String prefix = "a";

        List<List<String>> prefixedBase = base.stream()
                .map(subList -> Stream.concat(Stream.of(prefix), subList.stream())
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        System.out.println(prefixedBase); // 输出:[[a, foo], [a, bar]]
    }
}

注意:List.of()生成的是不可变列表,所以必须创建新列表来存储结果,不能直接修改原子列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:26:01