Nuñito Calzada
Nuñito Calzada

Reputation: 2076

Java8: collecting a stream into a SortedMap by key

I want to collect a stream into a Map where has the keys sorted, so I tried :

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(), 

But I got a compilation error

Type mismatch: cannot convert from Map<LocalDate,Object> to 
 TreeMap<LocalDate,MenuChart2.Statistics>

Upvotes: 2

Views: 835

Answers (2)

AJNeufeld
AJNeufeld

Reputation: 8695

If you are storing your data in a sorted map, like a TreeMap, you don't need to create a .sorted() version of the stream; the collector will naturally sort the data as it stores it in the TreeMap.

Your .collect() call must return a TreeMap in order for the result to be assigned to a TreeMap, so Collectors.toMap() must take a supplier that creates a TreeMap for the collector, to allow the propagation of the required type.

Eg)

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}

The resulting TreeMap shows the data is sorted by key.

Upvotes: 6

carles xuriguera
carles xuriguera

Reputation: 980

Map<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());

TreeMap<LocalDate, , MenuChart2.Statistics> last3MPerDaySorted = new TreeMap<LocalDate, MenuChart2.Statistics>(last3MPerDay);

Upvotes: 1

Related Questions