在Java中动态生成2个列表的非重复排列对

我一直在看很多关于Java中排列的不同post,但是没有一个符合我的账单,所以我决定发帖。

所以我有2个List ,我需要生成没有重复的所有排列对 ,其中该对的一个元素在第一个列表中,第二个元素在第二个列表中。

例如,如果我有:

 List l1 = Arrays.asList(new Integer[] {1, 2, 3}); List l1 = Arrays.asList(new Integer[] {2, 3, 4}); 

然后我想输出:

 (1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4) 

注意,(3,2)不在这里,因为我已经有(2,3)

我找不到任何库甚至远程关闭的东西,我发现guavaPermutations有类似的东西,但似乎最近已经停产或其他东西。

此外,我不想将列表存储在内存中,因为它可能非常大,我只需要一次迭代一对,所以我试图找到生成它们的方法。 我正在考虑实现一个Iterable但我似乎无法编写看起来很有效的东西。

如果你知道那些已经做过这种东西的图书馆也会非常有用!

怎么样

 class Pair { private int x, y; Pair(int x, int y) { this.x = x; this.y = y; } @Override public int hashCode() { int result = 1; result = 31 * result + x; result = 31 * result + y; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!(obj instanceof Pair)) return false; Pair tmp = (Pair) obj; return (tmp.x == x && tmp.y == y) || (tmp.x == y && tmp.y == x); } public String toString() { return "(" + x + "," + y + ")"; } } class Testt { public static void main(String[] args) { List l1 = Arrays.asList( 1, 2, 3 ); List l2 = Arrays.asList( 2, 3, 4 ); Set set = new HashSet(); for (int i : l1) for (int j : l2) set.add(new Pair(i, j)); System.out.println(set); } } 

产量

 [(1,2), (1,3), (1,4), (2,2), (2,3), (2,4), (3,3), (3,4)]