Java 从每个键的一个项目中获取所有可能的组合

标签 java java-8 hashmap permutation guava

我正在尝试从 Map<String,List<String>> 中获取所有可能性. 我想每个键只获得一个项目,例如:

 Map<String, List<String>> map = new HashMap<>();
    map.put("first", asList("first1", "first2", "first3"));
    map.put("second", asList("second1", "second2", "second3"));
    map.put("anyOther", asList("anyType1", "anyType2", "anyType3"));

我想要每个键一个项目并从其他键获取所有可能的值,例如:

first1;second1;anytype1
first1;second2;anytype2
first1;second3;anytype3
first1;second1;anytype1
first1;second2;anytype3
first1;second3;anytype2
.....

你们知道我该怎么做吗?我可以更改我的数据结构,也许使用 POJO 或类似的东西。

最佳答案

你想要 Lists#cartesianProduct(List<List>) :

final List<List<String>> product = 
    Lists.cartesianProduct(ImmutableList.copyOf(map.values()));
System.out.println(product);
// prints: [[anyType1, first1, second1], [anyType1, first1, second2], [anyType1, first1, second3], [anyType1, first2, second1], [anyType1, first2, second2], [anyType1, first2, second3], [anyType1, first3, second1], [anyType1, first3, second2], [anyType1, first3, second3], [anyType2, first1, second1], [anyType2, first1, second2], [anyType2, first1, second3], [anyType2, first2, second1], [anyType2, first2, second2], [anyType2, first2, second3], [anyType2, first3, second1], [anyType2, first3, second2], [anyType2, first3, second3], [anyType3, first1, second1], [anyType3, first1, second2], [anyType3, first1, second3], [anyType3, first2, second1], [anyType3, first2, second2], [anyType3, first2, second3], [anyType3, first3, second1], [anyType3, first3, second2], [anyType3, first3, second3]]

关于Java 从每个键的一个项目中获取所有可能的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53412072/

相关文章:

java - 如果发生超时,则使用相同事件自动调用 Lambda

java - 计算多个并发线程的流量速度

java - Java 中对区域设置 (tn-ph) 和 (hmn-cn) 的支持

java - 如何使用Java8流和groupBy从 map 中获取多级聚合结果?

Java GC 开销超出限制

java - Netbeans 中带有 git 的版本号

java - 枚举的通用输入参数编译错误

java - IntStream 分步迭代

android - Hashmap有什么问题

java - HashMap 不调用 Object.equals?