之前作項目的時候計算笛卡爾積的時候,老是使用各類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