Java8 Map的总和

时间:2019-05-21 03:23:28

标签: java java-8 java-stream

是否可以在1行中使用Java8编写以下所有空字符串检查和空字符串检查?

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());
    }
}

类似以下内容

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

2 个答案:

答案 0 :(得分:6)

怎么样,

ViewPager2(context)

答案 1 :(得分:4)

以下代码可能是解决方案:

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();