Skip to content

incompatible types: no instance(s) of type variable(s) F,T exist so that java.util.Collection conforms to java.util.Set<java.lang.Long

I am trying to convert the list of ComplexItem to a list of their corresponding IDs Long. But getting the above error which doesn’t go even after typecasting the getCollection() call with (Collection<ComplexItem>)

Set<Long> ids = Collections2.transform(
                    getComplexItems(), new Function<ComplexItem, Long>() {
                        @Override public Long apply(final ComplexItem item) {

 public List<ComplexItem> getComplexItems() {


There’s no reason to expect that the result of Collections2.transform, which is a Collection, will be magically transformed to a Set. This is the reason for the type matching error in the title. You’ll need either to convert the result to a set explicitly or make do with the Collection.

Since you’re already using Guava, you should strongly consider ImmutableSet, so it’s

ImmutableSet<Long> ids 
    = ImmutableSet.copyOf(Collections2.transform(getComplexItems(), item ->;

Taking a step back, remember Guava was created before Java Streams. It’s generally preferable to use language built-ins rather than a third party library, even when it’s as good as Guava. In other words, prefer

getComplextItems().stream().map(item ->;

where toImmutableSet() is a collector defined by ImmutableSet.