Nuñ*_*ada 1 java collections functional-programming java-8 java-stream
我想将流收集到Map中,其中的键已排序,所以我尝试了:
TreeMap<LocalDate, MenuChart2.Statistics> last3MPerDay =
menuPriceByDayService.findAllOrderByUpdateDate(menu, DateUtils.quarterlyDate(), 92)
.stream()
.sorted(comparing(MenuPriceByDay::getUpdateDate))
.collect(Collectors
.toMap(MenuPriceByDay::getUpdateLocalDate, p -> new MenuChart2().new Statistics( p.getMinPrice().doubleValue(),
Run Code Online (Sandbox Code Playgroud)
但是我遇到了编译错误
Type mismatch: cannot convert from Map<LocalDate,Object> to
TreeMap<LocalDate,MenuChart2.Statistics>
Run Code Online (Sandbox Code Playgroud)
如果您将数据存储在排序的映射中(如)TreeMap,则无需创建.sorted()流的版本;收集器会自然地对数据进行排序,并将其存储在TreeMap。
您的.collect()呼叫必须返回一个TreeMap,以便将结果分配给TreeMap,因此Collectors.toMap()必须接受TreeMap为收集器创建一个的供应商,以允许传播所需的类型。
例如)
jshell> String[] data = { "apple", "pear", "orange", "cherry" };
data ==> String[4] { "apple", "pear", "orange", "cherry" }
jshell> var map = Arrays.stream(data)
...> .collect(Collectors.toMap(s -> s,
...> s -> s.length(),
...> (a,b) -> a,
...> TreeMap::new));
map ==> {apple=5, cherry=6, orange=6, pear=4}
Run Code Online (Sandbox Code Playgroud)
结果TreeMap显示数据按键排序。