1

I am trying to sort items by the price, but each item belongs to a category so I have to create a map with categories as key and items as value and I have to sort it using Comparator class.

This is Comparator class

public class ProductionSorter implements Comparator<Item> {
    public ProductionSorter(){};

    @Override
    public int compare (Item a, Item b){
        return a.getSellingPrice().compareTo(b.getSellingPrice());
    }
}

This is the map

Map <Category, List<Item>> mapOfItems = items
                .stream()
                .collect(Collectors.groupingBy(Item::getCategory));

I am not sure how to sort items by price on this map.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
JurajC
  • 99
  • 2
  • 8

1 Answers1

4

The following should do the trick:

Map<String, List<Item>> mapOfItems = items.stream()
        .collect(Collectors.groupingBy(Item::getCategory,
                collectingAndThen(toList(), e -> e.stream().sorted(new ProductionSorter()).collect(toList()))));

With the following imports:

import java.util.*;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;

It is similar to what you have already but with the additional Collector so that you can define how you want your data to be collected.

You can read more about the collectingAndThen() at the reference documentation.

João Dias
  • 16,277
  • 6
  • 33
  • 45
  • Thanks a lot, but this e -> e.stream... is giving me problems. I'm getting an error "Incompatible parameter types in lambda expression: expected List but found List". – JurajC Nov 13 '21 at 17:07
  • 1
    That is weird, this is working on my side. Maybe you imported the wrong classes? I've added my imports to the answer. Please check them ;) – João Dias Nov 13 '21 at 17:11