CollectionUtils permutations() Example in Java

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


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<>();
        List<List<String>> newList = (List<List<String>>) CollectionUtils.permutations(firstList);

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