构建随机排列列表的最有效方法

对于给定的Collection aCollection ,如何构建一个ArrayList<OrderedCouple>其中包含ArrayList<OrderedCouple>所有可能的耦合排列(自耦合除外)。

例如,假设aCollection是包含teamAteamBteamCSet ,而OrderedCouple则是类Game ,其中构造函数接收两个团队,主机和guest作为参数。 我想在Team之间建立一个所有可能GameArrayList 。 也就是说, ArrayList将成为组{new Game(teamA, teamB), new Game(teamA, teamC), new Game(teamB, teamA), new Game(teamB, teamC), new Game(teamC, teamA), new Game(teamC, teamB)}以随机顺序。

我想不出比这更快的方法:

 @Test public void buildMatchUps() { List teams = Arrays.asList("A", "B", "C"); int s = teams.size() * teams.size() - teams.size(); List matchUps = new ArrayList(s); for(String host : teams) { for(String guest : teams) { if(host != guest) { // ref comparison, because the objects // come from the same list. Otherwise // equals should be used! matchUps.add(host + " : " + guest); } } } Collections.shuffle(matchUps); for(String matchUp : matchUps) { System.out.println(matchUp); } } 

打印这样的东西:

 C : A B : A A : C C : B B : C A : B