Jigar Naik
Jigar Naik

Reputation: 1994

Java8 Map of Map with sum

Is it possible to write below using Java8 in 1 line with all the null and empty string checks?

Map<Integer, Map<String, Object>> data = new HashMap<>(holdings.rowMap());

Set<Entry<Integer, Map<String, Object>>> entrySet = data.entrySet();
double transactedQuantity = 0;
for (Entry<Integer, Map<String, Object>> entry : entrySet) {
    Map<String, Object> value = entry.getValue();
    Object qty = value.get("quantity");
    if (qty != null && qty != "") {
        transactedQuantity += Double.valueOf(qty.toString());
    }
}

Something like below

data.values().stream().filter((k,v) -> k.equals("quantity") && v != null && v != "").flatMapToDouble(...);

Upvotes: 3

Views: 1116

Answers (2)

Anshul Singhal
Anshul Singhal

Reputation: 2201

Following code could be the solution:

double transactedQuantity  = data.values()
                .stream()
                .map(valueMap -> valueMap.get("quantity"))
                .filter(exactQuantity -> exactQuantity != null)
                .map(quantityInString -> quantityInString.toString())
                .filter(quantity -> !quantity.isEmpty())
                .mapToDouble(quantityInString -> Double.valueOf(quantityInString))
                .sum();

Upvotes: 4

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

How about this,

data.values().stream()
    .map(m -> m.get("quantity"))
    .filter(qty -> qty != null && qty != "")
    .mapToDouble(qty -> Double.valueOf(qty.toString()))
    .sum();

Upvotes: 5

Related Questions