繁体   English   中英

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

[英]Best way to replace nested loop concatenate string using java stream

我有一个names列表和一个versions列表。 我想获得通过连接两个列表中的字符串构造的所有排列。 我正在使用两个 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))));

有没有更好的方法来做到这一点?

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

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

请记住,操作非常昂贵。 Google 的 Guava 也在com.google.common.collect.Sets.cartesianProduct(s1, s2)下实现了这一点。

您应该期待在流式传输names使用flatMap ,然后进一步正确地执行map操作,如下所示:

List<String> result = names.stream() // for each name
        .flatMap(name -> versions.stream() // for each version
                .map(version -> name.concat(version))) // concat version to the name
        .collect(Collectors.toList()); // collect all such names

或者更整洁一点:

final List<String> result = names.stream()          // Stream the Names...
        .flatMap(name    -> versions.stream()       // ...together with Versions.
        .map    (version -> name.concat(version)))  // Combine Name+Version
        .collect(Collectors.toList());              // & collect in List.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM