gpt4 book ai didi

java - 如何在Java中将2d集合转换为1d?

转载 作者:行者123 更新时间:2023-12-03 18:21:00 25 4
gpt4 key购买 nike

有什么办法可以将2d Collection转换为1d

输出为:[[hello, hallo], [hi]]

要求的是:[hello,hallo,hi]

我的尝试:

Collection<Collection<String>> st = new ArrayList<>();
Collection<String> co1 = new ArrayList<>();
Collection<String> co2 = new ArrayList<>();
co1.add("hello");
co1.add("hallo");
co2.add("hi");
st.add(co1);
st.add(co2);
System.out.println(st);

最佳答案

如果您使用的是Java8 +,则可以使用以下方法:

Collection<String> result = st.stream().flatMap(Collection::stream).collect(Collectors.toList());


但是请注意,在此我不会单独处理重复项。

关于java - 如何在Java中将2d集合转换为1d?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60850607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com