Search code examples
javaguava

How to replace Guava's ImmutableSet.toImmutableSet() collector with an alternative, if you're stuck with using Guava 20.0?


I am hitting some Guava dependency issues that would require quite a bit of work to sort out. Due to a third-party library also depending on Guava, (which I unfortunately have to use), I have to downgrade my dependency of Guava from 27.0.1-jre all the way back to 20.0. It seems that there are no major side-effects other than the following bit of code now being broken, since the ImmutableSet.toImmutableSet() was only introduced in Guava 21.0:

ImmutableSet.toImmutableSet();

The full code block is:

cronJobDefinitions = cronJobsRegistry.get()
                                     .stream()
                                     .map(ThrowingFunction.unchecked(clazz -> clazz.newInstance()
                                                                                   .getCronJobDefinition()))
                                     .collect(ImmutableSet.toImmutableSet());

Is there a simple way to replace ImmutableSet.toImmutableSet() with an alternative in the JDK, maybe? I'm currently using JDK8, (but would be curious to hear, if there are better solutions in newer JDK-s).


Solution

  • You can collect it as a Set using Collectors.toSet. But there are no guarantees on the type of the returned Set. So, you can use Collectors.collectingAndThen to convert the above set into a Google Guava ImmutableSet.

    cronJobDefinitions = cronJobsRegistry.get()
        .stream()
        .map(..)
        .collect(Collectors.collectingAndThen(Collectors.toSet(), ImmutableSet::copyOf));