我正在尝试编写这个方法,它应该提供一个地图,每个条目都有:书名作为键,值作为集合中的副本数。
为了更好地澄清,
booksColl
是一个TreeMap<String,LinkedList<Book>>
,其中键是书名,值是代表其副本的书籍列表。
Eclipse 返回这种类型的错误
Type mismatch: cannot convert from Map<Object,Object> to SortedMap<String,Integer>
,我不明白为什么以及如何解决它,请你帮助我吗?
提前致谢,如果这个问题可能很愚蠢,我很抱歉。
/**
* 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;
}
我尝试强制转换 toMap 参数,但它也不起作用。
如果您想要
SortedMap
,您需要添加 TreeMap::new
作为最后一个参数。
SortedMap<String, Integer> res = this.booksColl.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, e->e.getValue().size(), TreeMap::new));
否则只需使用
Map
Map<String, Integer> res = this.booksColl.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, e->e.getValue().size()));