Sort using overriden method compare

Viewed 58

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.

1 Answers

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.

Related