Thursday, September 4, 2025
HomeLanguagesJavaSets powerSet() function | Guava | Java

Sets powerSet() function | Guava | Java

Guava’s Sets.powerSet() returns the set of all possible subsets of set.

Syntax:

public static <E> 
  Set<Set<E>> 
    powerSet(Set<E> set)

Here, set is the set of elements to construct a power set from.

Return Value: This method returns the power set, as an immutable set of immutable sets.

Exceptions:

  • IllegalArgumentException: If set has more than 30 unique elements, because this causes the power set size to exceed the int range.
  • NullPointerException: If set is or contains null.

Note: The power set of the empty set is not the empty set, but a one-element set containing the empty set.

Example 1:




// Java code to return the set of
// all possible subsets of a set
  
import com.google.common.collect.Sets;
import java.util.Set;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
  
        // Creating a set
        Set<Integer>
            set = Sets.newHashSet(1, 2, 3);
  
        // powerSet to store all subsets of a set
        Set<Set<Integer> >
            powerSet = Sets.powerSet(set);
  
        // Displaying all possible subsets of a set
        for (Set<Integer> s : powerSet)
            System.out.println(s);
    }
}


Output:

[]
[1]
[2]
[1, 2]
[3]
[1, 3]
[2, 3]
[1, 2, 3]

Example 2:




// Java code to return the set of
// all possible subsets of a set
  
import com.google.common.collect.Sets;
import java.util.Set;
  
class GFG {
  
    // Driver's code
    public static void main(String[] args)
    {
        // Creating a set
        Set<String>
            set = Sets.newHashSet("G", "F", "g");
  
        // powerSet to store all subsets of a set
        Set<Set<String> >
            powerSet = Sets.powerSet(set);
  
        // Displaying all possible subsets of a set
        for (Set<String> s : powerSet)
            System.out.println(s);
    }
}


Output:

[]
[F]
[G]
[F, G]
[g]
[F, g]
[G, g]
[F, G, g]

Note: While the power set of a set with size n is of size 2^n, its memory usage is only O(n). When the power set is constructed, the input set is merely copied. Only as the power set is iterated are the individual subsets created, and these subsets themselves occupy only a small constant amount of memory.

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32261 POSTS0 COMMENTS
Milvus
81 POSTS0 COMMENTS
Nango Kala
6626 POSTS0 COMMENTS
Nicole Veronica
11795 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11855 POSTS0 COMMENTS
Shaida Kate Naidoo
6747 POSTS0 COMMENTS
Ted Musemwa
7023 POSTS0 COMMENTS
Thapelo Manthata
6695 POSTS0 COMMENTS
Umr Jansen
6714 POSTS0 COMMENTS