In this post, we will see CollectionUtils permutations() example in Java. we will see how to use CollectionUtils permutations()
method. The permutations()
method returns all the permutations for a given list.
Syntax of permutations() method
public static <E> Collection<List<E>> permutations(final Collection<E> collection)
We need to add the below dependency in the maven to use org.apache.commons.collections4.CollectionUtils permutations()
method. We can download the apache-commons maven dependency from here.
pom.xml changes
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
CollectionUtils permutations() Example in Java
package com.javatute;
import org.apache.commons.collections4.CollectionUtils;
import java.util.ArrayList;
import java.util.List;
public class CollectionUtilsPermutationsExample {
public static void main(String[] args) {
List<String> firstList = new ArrayList<>();
firstList.add("Jon");
firstList.add("Mark");
firstList.add("Mike");
List<List<String>> newList = (List<List<String>>) CollectionUtils.permutations(firstList);
System.out.println(newList);
}
}
Output is
[[Jon, Mark, Mike], [Jon, Mike, Mark], [Mike, Jon, Mark], [Mike, Mark, Jon], [Mark, Mike, Jon], [Mark, Jon, Mike]]
How to generate all permutations of a List?
We can use CollectionUtils permutations() method.
Note – Internally permutations() method uses PermutationIterator class. In
That’s all about CollectionUtils permutations() Example in Java.
Related post
- CollectionUtils isEmpty() Example in Java.
- StringUtils isEmpty() and IsBlank() Example in Java.
- StringUtils join() Example in Java.
- CollectionUtils union() Example in Java
- CollectionUtils intersection() Example in Java
- CollectionUtils isEqualCollection() Example in Java
- StringUtils isAlpha() example in Java
- CollectionUtils retainAll() Example in Java
- CollectionUtils reverseArray() Example in Java
- CollectionUtils select() Example in Java
- CollectionUtils removeAll() Example in Java