Java 8 Streams here. I have the following classes:
public enum Category {
Thing,
Thang,
Fizz
}
@Data // using lombok to generate ctors/getters/setters/etc.
public class LineItem {
private Long id;
private String name;
private Category category;
private BigDecimal amount;
}
@Data
public class PieSlice {
private String label;
private BigDecimal value = BigDecimal.ZERO;
public void addAmount(BigDecimal amount) {
value = value.add(amount);
}
}
In my code I am given a List<LineItem> and I want to convert it to a Map<Category,PieSlice> using the Streams API, if at all possible.
Using the non-Stream way, the conversion would look like:
List<LineItem> lineItems = getSomehow();
Map<Category,PieSlice> sliceMap = new HashMap<>();
PieSlice thingSlice = new PieSlice();
PieSlice thangSlice = new PieSlice();
PieSlice fizzSlice = new PieSlice();
for (LineItem lineItem : lineItems) {
if (lineItem.getCategory().equals(Category.Thing)) {
thingSlice.addAmount(lineItem.getAmount());
} else if (lineItem.getCategory().equals(Category.Thang)) {
thangSlice.addAmount(lineItem.getAmount());
} else if (lineItem.getCategory().equals(Category.Fizz)) {
fizz.addAmount(lineItem.getAmount());
} else {
throw new RuntimeException("uncategorized line item");
}
}
sliceMap.put(Category.Thing, thingSlice);
sliceMap.put(Category.Thang, thangSlice);
sliceMap.put(Category.Fizz, fizzSlice);
The problem is that I need to edit the code every time I add a new Category. Is there a way to do this via the Streams API, regardless of what Category values exist?
Category?