I have an entity
public class Report {
private String departmentName;
private BigDecimal amount;
private String currency;
}
and I want to calculate the amount for each department depending on the currency and write the result in the line. Example:
List<Report> list = new ArrayList<>();
list.add(new Report("Moscow", new BigDecimal(100), "USD"));
list.add(new Report("Moscow", new BigDecimal(100), "USD"));
list.add(new Report("Paris", new BigDecimal(100), "USD"));
list.add(new Report("Moscow", new BigDecimal(200), "RUR"));
Result: "Moscow 200 usd, Paris 100 USD, Moscow 200 RUR"
For it:
Map<String, Map<String, String>> collect = list.stream().collect(
Collectors.groupingBy(doc -> doc.getDepartmentName(),
Collectors.groupingBy(Report::getCurrency,
Collectors.collectingAndThen(Collectors.toList(), doc -> {
BigDecimal sum = doc.stream()
.map(A::getAmount)
.filter(Objects::nonNull)
.reduce(BigDecimal.ZERO, BigDecimal::add);
String cur = doc.stream().map(Report::getCurrency)
.findFirst().get();
return sum.toString() + " " + cur;
}))));
And I receive a result:
{Paris={USD=100 USD}, Moscow={USD=200 USD, RUR= 200 RUR}} -- correct
but I don't know how to convert Map<String, Map<String, String>> to String
.toString()) to show the above result. Adding example of desired output format would greatly help.