简体   繁体   中英

Java 8 groupingBy on generic collection

I'm rather new to Java generics and I have a problem using Java 8 groupingBy .

I need to implement a container of tweets which has the following interface:

public interface TweetsContainer<T extends Tweet> extends Iterable<T>, Serializable {
...
    Map<String, Collection<T>> groupByLang();
...
}

Tweet is my own class with properly implemented hashcode , equals , etc.

Here is my attempt to implement method groupByLang :

public class LinkedListTweetsContainer<T extends Tweet> implements TweetsContainer<T> {
    private final List<T> tweets;
...
    @Override
    public Map<String, Collection<T>> groupByLang() {
        Map<String, Collection<T>> res =
            tweets.stream().collect(Collectors.groupingBy(T::getLang));
        return res;
    }
...
}

However, I get an error at T::getLang , saying

Error:(51, 36) java: incompatible types: inference variable R has incompatible bounds
    equality constraints: java.util.Map<java.lang.String,java.util.List<T>>
    upper bounds: java.util.Map<java.lang.String,java.util.Collection<T>>,java.lang.Object

Tweet class has public method getStringID :

public class Tweet implements Serializable {
...
    public String getLang() { return lang; }
...
}

What does the error mean and what I'm doing wrong?

Update

@Radiodef, thanks for your answer, but I wanted to dig into a question a bit deeper. List is a Collection, isn't it? I know term covariance -- when we have classes A, B, B extends A, and we are talking about inheritance of GenericClass<A> and GenericClass<B> . Here we have the opposite situation: the same parametrized type, but different (nested) generic classes. What are Java rules in this case, or what keywords/terms should I keep in mind if I want to read about it myself?

groupingBy collects to a Map<K, List<T>> .

Map<String, List<T>> res =
//          ^^^^^^^
    tweets.stream().collect(Collectors.groupingBy(T::getLang));

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