【发布时间】:2018-04-27 04:21:39
【问题描述】:
我有两个集合——国家和州。我想从两者中创建所有可能的排列。
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);
}
}
州或国家/地区或两者的排列可以为空。我仍然希望我的代码能够正常运行。
要求
-
如果状态排列为空,则最终输出应为 [Houston USA, Houston United States of America]
-
如果国家/地区排列为空,则最终输出应为 [Houston TX, Houston Texas]
-
如果两者都为null,则不输出
我已将代码更改为以下
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());
这满足 3。当任一排列为空时,不满足 1 和 2。我没有得到别名作为回应。如何修改我的代码?
【问题讨论】:
标签: java string set java-stream permutation