使用Java Streams从两个集合创建排列

时间:2017-11-07 10:46:04

标签: lambda java-stream

我有两套 - 国家和州。我想从两者中创建所有可能的排列。

import java.util.*;
import java.util.stream.Collectors;

public class HelloWorld{

     public static void main(String []args){
        System.out.println("Hello World");

        Set<String> countryPermutations = new HashSet<>(Arrays.asList("United States of america", "USA"));

        Set<String> statePermutations = new HashSet<>(Arrays.asList("Texas", "TX"));

        Set<String> stateCountryPermutationAliases = countryPermutations.stream()
        .flatMap(country -> statePermutations.stream()
        .map(state -> state + country))
        .collect(Collectors.toSet());

        System.out.println(stateCountryPermutationAliases);
     }
    }

这给出了输出

[TexasUSA, TXUSA, TXUnited States of america, TexasUnited States of america]
然而,我想要相反的连接 - 国家+州。我如何扩展我的lambda来做到这一点?

1 个答案:

答案 0 :(得分:3)

 Set<String> stateCountryPermutationAliases = countryPermutations.stream()
            .flatMap(country -> statePermutations.stream()
                    .flatMap(state -> Stream.of(state + country, country + state)))
            .collect(Collectors.toSet());