So you want to find all the nonempty subsets of Set that will be {a} {b} {ab} for the set {ab}? This may not be the quickest solution, but you can go through all the elements in your set one by one, start from the first and define all nonempty sets β the first element, go to the second element and copy all the sets saved so far and add to all copied a new item plus and a new set with only a new item. Now you have all the subsets of the previous elements plus the set of all these sets with the element added added plus one with the new element. This can then be repeated for all elements and should yield all nonempty subsets.
Set<String> inputSet = new HashSet<String>(); inputSet.add("a"); inputSet.add("b"); inputSet.add("c"); inputSet.add("d"); List<Set<String>> subSets = new ArrayList<Set<String>>(); for(String addToSets:inputSet) { List<Set<String>> newSets = new ArrayList<Set<String>>(); for(Set<String> curSet:subSets) { Set<String> copyPlusNew = new HashSet<String>(); copyPlusNew.addAll(curSet); copyPlusNew.add(addToSets); newSets.add(copyPlusNew); } Set<String> newValSet = new HashSet<String>(); newValSet.add(addToSets); newSets.add(newValSet); subSets.addAll(newSets); } for(Set<String> set:subSets) { for(String setEntry:set) { System.out.print(setEntry + " "); } System.out.println(); }
What will be output:
ddbbdcdbcbccdadbabadc adbcabcacaa
source share