SortedMap operations
I need to implement a method maxPricePerProductType
that returns the maximum bid price for a product type, the products are sorted alphabetically. Products without offers are not counted. The method prototype is:
public SortedMap<String, Integer> maxPricePerProductType() { //use toMap
return null;
}
My classes
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 the map bids
contains the parameters that the group should buy. For example, he Group G1
wants to buy smartphones, and they have 3 rates: B1, B2 and B3. B1 costs 10, B2 15 and B3 7. G2 wants to buy smartphones too. It has 2 stakes. B4 costs 5 and B5 costs 20. So I need to take B1, B2, B3, B4 and B5 (since all bets are for the same product type) and add B5 as the key and 20 as the value to the sorted card. In short, I need to accept bids from each group, group them by product type, and add the one with the highest price per sorted card. This is what I was trying 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 proceed or this part is right.
source to share
It is misleading what is holding back private Map<String, Gruppo> groups = new HashMap<>();
and up Map<String, Bid> bids = new HashMap<>();
. If the keys on these cards are B1, B2...
and G1, G2...
are the actual names you really don't need as this information is present in each one anyway. Therefore, they must be List
s.
If there is something else, you can 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))));
source to share