gpt4 book ai didi

java - 使用java流替换嵌套循环连接字符串的最佳方法

转载 作者:行者123 更新时间:2023-11-30 01:40:46 24 4
gpt4 key购买 nike

我有一个名称列表和一个版本列表。我想获得通过连接两个列表中的字符串构造的所有排列。我使用两个 for 循环来执行此操作,但我想切换到更实用的风格方法。这是我的解决方案:

List<String> names = new ArrayList<>();
List<String> versions = new ArrayList<>();
List<String> result = new ArrayList<>();
names.forEach(name -> versions.stream().map(version -> result.add(name.concat(version))));

有更好的方法吗?

最佳答案

您正在寻找名称版本的“笛卡尔积”——基本上是上述集合/列表的返回集合/列表。

final Stream<List<String>> result = names.stream()
.flatMap(s1 -> versions.stream().flatMap(s2 -> Stream.of(Arrays.asList(s1, s2))));
result.forEach(System.out::println);

Keep in mind that operation is super expensive. Google's Guava have this implemented also under com.google.common.collect.Sets.cartesianProduct(s1, s2).

关于java - 使用java流替换嵌套循环连接字符串的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60119305/

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