Java tutorial
//package com.java2s; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Map; public class Main { /** * Returns a List of Lists: all combinations of the elements of the given * List. * * @param maxCombinationSize combinations larger than this value are * discarded */ public static List combinations(List original, int maxCombinationSize) { return combinations(original, maxCombinationSize, null); } /** * Returns a List of Lists: all combinations of the elements of the given * List. * * @param maxCombinationSize combinations larger than this value are * discarded * @param mandatoryItem an item that all returned combinations must contain, * or null to leave unspecified */ public static List combinations(List original, int maxCombinationSize, Object mandatoryItem) { ArrayList combinations = new ArrayList(); //Combinations are given by the bits of each binary number from 1 to 2^N for (int i = 1; i <= ((int) Math.pow(2, original.size()) - 1); i++) { ArrayList combination = new ArrayList(); for (int j = 0; j < original.size(); j++) { if ((i & (int) Math.pow(2, j)) > 0) { combination.add(original.get(j)); } } if (combination.size() > maxCombinationSize) { continue; } if ((mandatoryItem != null) && !combination.contains(mandatoryItem)) { continue; } combinations.add(combination); } return combinations; } /** * Returns a List of Lists: all combinations of the elements of the given * List. */ public static List combinations(List original) { return combinations(original, original.size(), null); } public static Object get(Class c, Map map) { if (map.keySet().contains(c)) { return map.get(c); } for (Iterator i = map.keySet().iterator(); i.hasNext();) { Class candidateClass = (Class) i.next(); if (candidateClass.isAssignableFrom(c)) { return map.get(candidateClass); } } return null; } }