Search code examples
javaparallel-processingsetjava-streampowerset

Using Java Streams to operate on an integer power set


I am generating a power set (Set<Set<Integer>>) from an original set (Set<Integer>).

i.e. {1, 2, 3} -> { {}, {1}, {2}, {3}, {1,2}, {2,3}, {1,3}, {1,2,3} }

Then I am using an isClique(Set<Integer>) method that returns a boolean if the given set is a clique in the adjacency matrix I am using.

I want to use a java stream to parallelize this operation and return the largest subset that is also a clique.

I am thinking something like this, but every variation I come up with causes a variety of compilation errors.

Optional result = powerSet.stream().parallel().
    filter(e ->{return(isClique(e));}).
    collect(Collectors.maxBy(Comparator Set<Integer> comparator));

I either get:

MaxClique.java:86: error: incompatible types: Stream<Set<Integer>> cannot be converted to Set<Integer>
    currentMax = powerSet.stream().parallel().filter(e -> { return (isClique(e));});//.collect(Collectors.maxBy(Comparator <Set<Integer>> comparator));

or something related to the comparator (which I'm not sure I'm doing correctly).

Please advise, thanks.


Solution

  • You have some syntax problems. But beside that, you can compute the same optional using:

    Optional<Set<Integer>> result = powerSet.stream().parallel()
        .filter(e -> isClique(e))
        .collect(
           Collectors.maxBy(
               (set1, set2) -> Integer.compare(set1.size(), set2.size())
           )
        );
    

    This is filtering based on your condition, then pulling the max value based on a comparator that compares set sizes.