jsp
jsp

Reputation: 13

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

I have String "ORIGINAL_PAYMODE:90.23,VOUCHRE:30.10,ORIGINAL_PAYMODE:80.30,VOUCHRE:33.10" i need to Split and add all ORIGINAL_PAYMODE value occurring in String using stream api

In this case I need result of 90.23+80.30 = 170.53

code :

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

Upvotes: 1

Views: 259

Answers (1)

ernest_k
ernest_k

Reputation: 45309

The easy step from what you have is to map it to a double stream, then sum().

I'm also splitting on the comma as it seems to be what separates your key/value pairs.

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

Upvotes: 1

Related Questions