我正在尝试从 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/