代码改变世界

使用Guava来计算笛卡尔积

2014-03-27 15:02  Rollen Holt  阅读(3907)  评论(0编辑  收藏  举报

以前做项目的时候计算笛卡尔积的时候,总是使用各种for循环来嵌套,最后往往在Sonar代码检查的时候总是会报警说for循环嵌套过深。

今天才知道Guava原来已经为我们提供了优雅的计算笛卡尔积的方法。

 

比如我们要计算3个List的笛卡尔积,每个list的内容都是['a', 'b', 'c'], 请看下面的代码:

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);
        }
    }
}

  输出为:

[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]