Java 11 here. I have the following POJOs:
public enum Category {
Dogs,
Cats,
Pigs,
Cows;
}
@Data // using Lombok to generate getters, setters, ctors, etc.
public class LineItem {
private String description;
private Category category;
private BigDecimal amount;
}
@Data
public class PieSlice {
private BigDecimal value;
private BigDecimal percentage;
}
I will have a lineItemList : List<LineItem> and want to convert them into a Map<Category,PieSlice> whereby:
- the
Categorykey represents all the distinctCategoryvalues across all thelineItemListelements; and - each
PieSlicevalue is created such that:- its
valueis a sum of all theLineItem#amountthat reference the sameCategory; and - its
percentageis a ratio of thePieSlice#value(the sum of alllineListItemelements mapped to theCategory) and the total amount of allLineItem#amounts combined
- its
For example:
List<LineItem> lineItemList = new ArrayList<>();
LineItem dog1 = new LineItem();
LineItem dog2 = new LineItem();
LineItem cow1 = new LineItem();
dog1.setCategory(Category.Dogs);
dog2.setCategory(Category.Dogs);
cow1.setCategory(Category.Cows);
dog1.setAmount(BigDecimal.valueOf(5.50);
dog2.setAmount(BigDecimal.valueOf(3.50);
cow1.setAmount(BigDecimal.valueOf(1.00);
Given the above setup I would want a Map<Category,PieSlice> that looks like:
- only has 2 keys,
DogsandCows, because we only have (in this example) Dogs and Cows - the
PieSlicefor Dogs would have:- a
valueof9.00because5.50+3.50is9.00; and - a
percentageof0.9, because if we take the total amounts of all dogs + all cows, we have a total value of10.0; Dogs comprise9.00 / 10.00or0.9(90%) of the total animals
- a
- the
PieSlicefor Cows would have:- a
valueof1.00; and - a
percentageof0.1
- a
My best attempt only yields a Map<Category,List<LineItem>> which is not what I want:
List<LineItem> allLineItems = getSomehow();
Map<Category,List<LineItem>> notWhatIWant = allLineItems.stream()
.collect(Collectors.groupingBy(LineItem::getCategory());
Can anyone spot how I can use the Streams API to accomplish what I need here?