简体   繁体   中英

incompatible types: no instance(s) of type variable(s) F,T exist so that java.util.Collection<T> 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) {
                            return item.id;
                        }
                    }));

 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 -> item.id)));

Taking a step back, remember Guava was created before Java Stream s. 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 -> item.id).collect(toImmutableSet());

where toImmutableSet() is a collector defined by ImmutableSet .

you got in the wrong import for Function

try this

    Collection<Long> ids = Collections2.transform(
        getComplexItems(), new com.google.common.base.Function<ComplexItem, Long>() {
            @Override public Long apply(final ComplexItem item) {
                return item.id;
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM