Java Set sub set getSubsets(Set set)

Here you can find the source of getSubsets(Set set)

Description

get Subsets

License

Apache License

Declaration

public static <T> List<Set<T>> getSubsets(Set<T> set) 

Method Source Code

//package com.java2s;
/**/* w w  w . j a va  2  s. c om*/
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static <T> List<Set<T>> getSubsets(Set<T> set) {
        List<Set<T>> subsets = new ArrayList<Set<T>>();
        List<T> list = new ArrayList<T>(set);
        int numOfSubsets = 1 << set.size();
        for (int i = 0; i < numOfSubsets; i++) {
            Set<T> subset = new HashSet<T>();
            for (int j = 0; j < numOfSubsets; j++) {
                if (((i >> j) & 1) == 1) {
                    subset.add(list.get(j));
                }
            }
            if (!subset.isEmpty()) {
                subsets.add(subset);
            }
        }
        Collections.sort(subsets, new Comparator<Set<T>>() {
            @Override
            public int compare(Set<T> o1, Set<T> o2) {
                return o1.size() - o2.size();
            }
        });
        return subsets;
    }
}

Related

  1. getFirstSubString(String s, Set delimiters)
  2. split(Set original, int subsetSize)
  3. sub(Set a, Set b)
  4. subset(double[] vals, boolean[] select)
  5. subset(Set sub, Set sup)