FearUs FearUs - 1 year ago 104
Java Question

All possible combinations of an array

I have an string array

{"ted", "williams", "golden", "voice", "radio"}

and I want all possible combinations of these keywords in the following form:

"ted williams",
"ted golden",
"ted voice",
"ted radio",
"williams golden",
"williams voice",
"williams radio",
"golden voice",
"golden radio",
"voice radio",
"ted williams golden",
"ted williams voice",
"ted williams radio",
.... }

I've been going for hours with no effective result (side effect of high-level programming ??).

I know the solution should be obvious but I'm stuck, honestly ! Solutions in Java/C# are accepted.


  1. It's not a homework

  2. "ted williams" and "williams ted" are considered the same, so I want "ted williams" only

EDIT 2: after reviewing the link in the answer, it turns out that Guava users can have the powerset method in com.google.common.collect.Sets

Answer Source

EDIT: As FearUs pointed out, a better solution is to use Guava's Sets.powerset(Set set).

EDIT 2: Updated links.

Quick and dirty translation of this solution:

public static void main(String[] args) {

    List<List<String>> powerSet = new LinkedList<List<String>>();

    for (int i = 1; i <= args.length; i++)
        powerSet.addAll(combination(Arrays.asList(args), i));


public static <T> List<List<T>> combination(List<T> values, int size) {

    if (0 == size) {
        return Collections.singletonList(Collections.<T> emptyList());

    if (values.isEmpty()) {
        return Collections.emptyList();

    List<List<T>> combination = new LinkedList<List<T>>();

    T actual = values.iterator().next();

    List<T> subSet = new LinkedList<T>(values);

    List<List<T>> subSetCombination = combination(subSet, size - 1);

    for (List<T> set : subSetCombination) {
        List<T> newSet = new LinkedList<T>(set);
        newSet.add(0, actual);

    combination.addAll(combination(subSet, size));

    return combination;


$ java PowerSet ted williams golden
[[ted], [williams], [golden], [ted, williams], [ted, golden], [williams, golden], [ted, williams, golden]]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download