Java List Combine combine(List list, int maxK)

Here you can find the source of combine(List list, int maxK)

Description

combine

License

Open Source License

Declaration

private static <T> List<List<T>> combine(List<T> list, int maxK) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.List;

public class Main {
    private static <T> List<List<T>> combine(List<T> list, int maxK) {
        List<List<T>> combinations = new ArrayList<>();
        for (int i = 1; i <= maxK; i++) {
            combinations.addAll(getCombinations(list, i));
        }//from  w  w w  .  j  a  va 2  s.  c  o  m
        return combinations;
    }

    private static <T> List<List<T>> getCombinations(List<T> list, int k) {
        List<List<T>> combinations = new ArrayList<>();
        if (k == 0) {
            combinations.add(new ArrayList<T>());
            return combinations;
        }
        for (int i = 0; i < list.size(); i++) {
            T element = list.get(i);
            List<T> rest = getSublist(list, i + 1);
            for (List<T> previous : getCombinations(rest, k - 1)) {
                previous.add(element);
                combinations.add(previous);
            }
        }
        return combinations;
    }

    private static <T> List<T> getSublist(List<T> list, int i) {
        List<T> sublist = new ArrayList<T>();
        for (int j = i; j < list.size(); j++) {
            sublist.add(list.get(j));
        }
        return sublist;
    }
}

Related

  1. combine(List commands, int startAt, int endAt)
  2. combine(List strlist, String delimiter)
  3. combine(List tokens, String separator)
  4. combine(List a, List b)
  5. combine(List dest, Collection... src)
  6. combine(List... dests)
  7. combineAfterIndexWithQuotes(List commands, String match)
  8. combineArray(List> data)
  9. combineArray(List... p)