2017-11-07 13 views
2

2つのセット - 国と州があります。私は両方からすべての可能な順列を作成したいと思います。国+状態 -Javaストリームを使用して2つのセットから順列を作成する

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] 

を与えます。これを行うためにラムダをどのように拡張できますか?

答えて

3
Set<String> stateCountryPermutationAliases = countryPermutations.stream() 
      .flatMap(country -> statePermutations.stream() 
        .flatMap(state -> Stream.of(state + country, country + state))) 
      .collect(Collectors.toSet()); 
関連する問題