Akash Kumar singh
Akash Kumar singh

Reputation: 49

Accessing elements of HashSet of HashSets

I have made a HashSet of HashSets. I want to access the Integer Values inside the subsets. My HashSet of HashSets is the set containing all the subsets of a Set which looks like this:-

[[], [1], [2], [1, 2], [3], [1, 3], [4], [1, 4], [2, 3], [1, 2, 3], [2, 4], [3,4], [1, 2, 4], [1, 3, 4], [2, 3, 4], [1, 2, 3, 4]].

enter code here

The code looks like this:

public class Subsets {
public static void main(String[] args){
    Set<Set<Integer>> subsets1 = new HashSet<Set<Integer>>();
    Set<Integer> mySet = new HashSet<Integer>();
     mySet.add(1);
     mySet.add(2);
     mySet.add(3);
    subsets1 = powerSet(mySet);
        }
public static <E> Set<Set<E>> powerSet(Set<E> originalSet) {
    Set<Set<E>> sets = new HashSet<Set<E>>();
    if (originalSet.isEmpty()) {
        sets.add(new HashSet<E>());
        return sets;

    }
    List<E> list = new ArrayList<E>(originalSet);
    E head = list.get(0);
    Set<E> rest = new HashSet<E>(list.subList(1, list.size())); 
    for (Set<E> set : powerSet(rest)) {
        Set<E> newSet = new HashSet<E>();
        newSet.add(head);
        newSet.addAll(set);
        sets.add(newSet);
        sets.add(set);
    }       
    return sets;
}
    }

Upvotes: 0

Views: 3980

Answers (1)

jgroehl
jgroehl

Reputation: 134

If you are using java8 you could use the forEach method to get to the nested Set<Integer> and calling yet another forEachto get to the underlying Integer values.

Inline code sample to syso all your Integer values:

subsets1.forEach(s -> s.forEach(s2 -> System.out.println(String.valueOf(s2))));

Multiline code sample to do somewhat more qualified operations:

subsets1.forEach(s -> {
        System.out.println("New set: ");
        s.forEach(s2 -> {
            System.out.println(String.valueOf(s2));
        });
    });

This would produce this output with your given example:

New set: 
New set: 
1
New set: 
2
New set: 
1
2
New set: 
3
New set: 
1
3
New set: 
2
3
New set: 
1
2
3

Is this what you were looking for?

As a none java8 user you could loop through the sets containing the Integer values:

for(Set<Integer> set : subsets1)
    {
        for(Integer i : set)
        {
            System.out.println(i);
        }
    }

Be thoughtful about using int or Integerin the nested loop as autoboxing / auto-unboxing can cause tremendous performance issues at runtime.

Upvotes: 1

Related Questions