Vincenzo Cosi
Vincenzo Cosi

Reputation: 187

operations on sortedMap

I have to implement the method maxPricePerProductType which returns the max price of the bids for product type, the products are alphabetically-sorted. Products whithout bids are not considered. The prototype of the method is:

public SortedMap<String, Integer> maxPricePerProductType() { //use toMap

    return null;
}

My classes are

public class GroupHandling {
    private Map<String, Group> groups = new HashMap<>();

    public SortedMap<String, Integer> maxPricePerProductType() { //use toMap

         return null;
      }
}

public class Group {
    private String name;
    String productType;
    Map<String, Bid> bids = new HashMap<>();

    public String getProductType() {
        return productType;
    }
}
public class Bid {
    String name;
    Group g;
    int price;

    public int getPrice() {
        return price;
    }

    public String getProductType(){
        return g.productType;
    }
}

Each group is interested in buying a certain type of product, and in the map bids are registered the options that the group have to buy products. For example the Group G1 wants to buy smartphones and they have 3 bids: B1, B2 and B3. B1 costs 10, B2 15 and B3 7. G2 wants to buy smartphones too. It has 2 bids. B4 costs 5 and B5 costs 20. So I have to take B1, B2, B3, B4 and B5 (since they are all bids for the same product type) and add to the sorted map B5 as key and 20 as value. In short, I need to take the bids from each group, group them by type of product and add the one with the highest price to a sorted map. This is what I tried to do:

public SortedMap<String, Integer> maxPricePerProductType() { //use toMap
    return groups.values().stream().
            flatMap(g -> g.bids.values().stream())
            .
             ;
}

But I don't know how to continue or if this part is right.

Upvotes: 3

Views: 101

Answers (1)

Eugene
Eugene

Reputation: 120848

It's sort of misleading what private Map<String, Gruppo> groups = new HashMap<>(); and Map<String, Bid> bids = new HashMap<>(); hold. If the keys in these maps are B1, B2... and G1, G2... - the actual names, than you don't really need them - since that information is present in each of them anyway. So these should really be Lists.

If there is something else, you could use:

 SortedMap<String, Integer> result = groups
            .values()
            .stream()
            .filter(g -> g.getBids() != null || !g.getBids().isEmpty())
            .flatMap(g -> g.getBids().values().stream())
            .collect(Collectors.groupingBy(b -> b.getGroup().getProductType(),
                    TreeMap::new,
                    Collectors.mapping(Bid::getPrice,
                            Collectors.collectingAndThen(Collectors.maxBy(Comparator.naturalOrder()), Optional::get))));

Upvotes: 3

Related Questions