Permutations of collection elements

In this post under Apache collections, I will explain with example, how to generate a collection of possible permutations of a particular collection elements.

If we have collection of elements, we can generate a list of different permutations containing the same elements.

The Apache Collections tool, has a “permutations” method in “CollectionUtils” class.

This method takes a collection as an argument and generates a collection of different permutations containing the elements from the input argument.

Below is the complete main code for your reference

Main class

1  package defaultPackage;
2  
3  import org.apache.commons.collections4.CollectionUtils;
4  
5  import java.util.ArrayList;
6  import java.util.Collection;
7  import java.util.List;
8  
9  public class Example13 {
10     public static void main(String[] args) {
11         List<String> list = new ArrayList<>(0);
12         list.add("h");
13         list.add("e");
14         list.add("l");
15         list.add("o");
16 
17         Collection<List<String>> output = CollectionUtils.permutations(list);
18         for(List<String> outputList : output) {
19             for(String data : outputList) {
20                 System.out.print(data);
21             }
22             System.out.println();
23         }
24     }
25 }

In the above code, at line 11, I create a list of String elements.

Then I populate them with strings. In this case “h”, “e”, “l”, “o” elements.

At line 17, I call “permutations” static method available in “CollectionUtils” and pass the list as an argument.

This method returns a Collection whose each entry is inturn a list of strings and it is assigned to “output” variable.

Basically this “output” variable will have a collection of every possible permutations of given collection elements.

From line 19 to 22, I print the collection elements to the console.

Below is the output

Output

helo
heol
hoel
ohel
ohle
hole
hloe
hleo
lheo
lhoe
lohe
olhe
oleh
loeh
leoh
leho
elho
eloh
eolh
oelh
oehl
eohl
ehol
ehlo

In this way we can generate permutations of input collection.

Leave a comment