Search code examples
javajava-stream

Issues with toMap, java streams


I'm trying to write this method which should provide a map, having for each entry: the title of the book as key and as value the number of its copies in the collection.

Just to clarify better, booksColl is a TreeMap<String,LinkedList<Book>>, where the key is the book title and the value a list of books representing its copies.

Eclipse returns this type of error Type mismatch: cannot convert from Map<Object,Object> to SortedMap<String,Integer>, I don't understand why and how I can solve it, please could you help me?

Thanks in advance and I'm sorry if the question might be stupid.

/**
 * Returns the book titles available in the library
 * sorted alphabetically, each one linked to the
 * number of copies available for that title.
 * 
 * @return a map of the titles liked to the number of available copies
 */
public SortedMap<String, Integer> getTitles() {     
    
    SortedMap<String, Integer> res = this.booksColl.entrySet().stream()
            .collect(Collectors.toMap(Entry::getKey,e->e.getValue().size()));
    return res;
}

I tried to cast the toMap parameters but It doesn't work either.


Solution

  • Personally, I feel this is the most readable solution

    SortedMap<String, Integer> res = new TreeMap<>();
    this.booksColl.forEach((key, val) -> res.put(key, val.size());
    

    Note that the two args Collectors.toMap(...) returns Map, not SortedMap

    Map<String, Integer> res = this.booksColl.entrySet().stream()
                .collect(Collectors.toMap(Entry::getKey, e->e.getValue().size()));
    

    If you want a SortedMap you'll need to use the four args Collectors.toMap(...)

    SortedMap<String, Integer> res = this.booksColl.entrySet().stream()
                .collect(Collectors.toMap(Entry::getKey, e->e.getValue().size(), (v1, v2) -> v1, TreeMap::new));