I have two Sets - country and state. I want to create all possible permutations from both.
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> stateCountryPermutations = countryPermutations.stream()
.flatMap(country -> statePermutations.stream()
.flatMap(state -> Stream.of(state + country, country + state)))
.collect(Collectors.toSet());
Set<String> finalAliases = Optional.ofNullable(stateCountryPermutations)
.map(Collection::stream).orElse(Stream.empty())
.map(sc -> "houston " + sc)
.collect(Collectors.toSet());
System.out.println(stateCountryPermutationAliases);
}
}
The state or country or both permutations can be null. I still want my code to function.
Requirements
If state permutation is null, final output should be [Houston USA, Houston United States of America]
If country permutations is null, final output should be [Houston TX, Houston Texas]
If both are null, then no output
I'm changed my code to below
Set<String> stateCountryPermutations =
Optional.ofNullable(countryPermutations)
.map(Collection::stream)
.orElse(Stream.empty())
.flatMap(country -> Optional.ofNullable(statePermutations)
.map(Collection::stream)
.orElse(Stream.empty())
.flatMap(state -> Stream.of(state + country, country + state)))
.collect(Collectors.toSet());
This satisfies 3. When either permutation is null, 1 & 2 are not satisfied. I get no aliases as response. How do I modify my code?