1

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

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.