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

时间:2018-11-21 12:29:34

标签: 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或类似的东西。

1 个答案:

答案 0 :(得分:4)

您想要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]]