之前作项目的时候计算笛卡尔积的时候,老是使用各类for循环来嵌套,最后每每在Sonar代码检查的时候老是会报警说for循环嵌套过深。java
今天才知道Guava原来已经为咱们提供了优雅的计算笛卡尔积的方法。blog
好比咱们要计算3个List的笛卡尔积,每一个list的内容都是['a', 'b', 'c'], 请看下面的代码:for循环
public class CartesianProductUtil { public static void main(String[] args) { ImmutableSet<Character> charList = ImmutableSet.of('a', 'b', 'c'); Set<List<Character>> set = Sets.cartesianProduct(charList, charList, charList); for (List<Character> characters : set) { System.out.println(characters); } } }
输出为:table
[a, a, a]
[a, a, b]
[a, a, c]
[a, b, a]
[a, b, b]
[a, b, c]
[a, c, a]
[a, c, b]
[a, c, c]
[b, a, a]
[b, a, b]
[b, a, c]
[b, b, a]
[b, b, b]
[b, b, c]
[b, c, a]
[b, c, b]
[b, c, c]
[c, a, a]
[c, a, b]
[c, a, c]
[c, b, a]
[c, b, b]
[c, b, c]
[c, c, a]
[c, c, b]
[c, c, c]class