-1

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.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126

2 Answers2

0

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.

ernest_k
  • 44,416
  • 5
  • 53
  • 99
0

Your major issue is using the wrong syntax for the comparator. Rather, you'd want something along the lines of:

Optional<Set<Integer>> resultSet = 
                    powerSet.stream()
                            .parallel()
                            .filter(e -> isClique(e))
                            .max(Comparator.comparingInt(Set::size));

Note the use of the max method as opposed to the maxBy, this is because the maxBy is typically used as a downstream collector. in fact, the real motivation for it to exist is to be used as a downstream collector.

Also, note the use of Optional<Set<Integer>> being the receiver type as opposed to Optional as in your example code snippet. The latter is a raw type and you should avoid to use them unless there is no choice.

Lastly, but not least, if you haven't already done so then I'd suggest you try executing the code sequentially first and if you think you can benefit from parallel streams then you can proceed with the current approach.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126