使用流 api Java 拆分字符串并添加和 Return 双精度值

Split String and Add and Return Double Value using stream api Java

我有字符串 "ORIGINAL_PAYMODE:90.23,VOUCHRE:30.10,ORIGINAL_PAYMODE:80.30,VOUCHRE:33.10" 我需要拆分并添加出现在字符串中的所有 ORIGINAL_PAYMODE 值流 api

在这种情况下,我需要的结果是 90.23+80.30 = 170.53

代码:

public static void main(String[] args) {
        
String reftype
="ORIGINAL_PAYMODE:90.23,VOUCHRE:30.10,ORIGINAL_PAYMODE:80.30,VOUCHRE:33.10";
Pattern COMMA = Pattern.compile(",");

Pattern p = Pattern.compile(":");

String result = COMMA.splitAsStream(reftype)
            .filter(role -> role.contains("ORIGINAL_PAYMODE"))
            .map(String::trim)
            .collect(Collectors.joining(","));

System.out.println(result);

根据您所拥有的,简单的一步是将其映射到双流,然后 sum()

我也在逗号上分开,因为它似乎是分隔你的 key/value 对的原因。

double sum = Arrays.stream(s.split(",")) //split as you wish or find efficient
                   .filter(v -> v.startsWith("ORIGINAL_PAYMODE"))
                   .map(v -> v.substring(v.indexOf(":") + 1).trim())
                   .mapToDouble(Double::parseDouble)
                   .sum()