Home > Blockchain >  How to get sum using java streams?
How to get sum using java streams?

Time:09-30

A B C
33 6 0
79 6 8
13 4 0
12 6 0
K100 6 0

Let's say I want to sum up the A values iff B = 6 and C = 0. So I would sum up 33 12 100 to get 145.

A can contain letters like K100 which should be ignored and handled like if it was 100. How can I achieve this using streams?

answer  = someObj.someList() # answer should be 145
.stream()
.filter(e -> e != null && e.getB() == 6 && e.getC == 0
... // what goes here?

CodePudding user response:

First, I am confused. Your question implies B and C are integers. But your commented solution is checking equality to strings. I am assuming only column A is a string. It is easily altered if not the case.

I would consider a slight improvement to the other answer. Integer.parseInt already returns an int so you can change the prior map to mapToInt In your example the final map simply reboxes the int value to extract an int value. I am using a record as a demo class.

record Data(String getA, int getB, int getC) {
};

public static void main(String[] args) {
    

List<Data> someList = new ArrayList<>(List.of(
        new Data("33", 6, 0), new Data("79", 6, 8),
        new Data("13", 4, 0), new Data("12", 6, 0),
        new Data("K100", 6, 0)));

long answer = someList.stream()
        .filter(e -> e != null && e.getB() == 6
                && e.getC() == 0)
        .mapToInt(e -> Integer.parseInt(
                e.getA().replaceAll("\\D", "")))
        .sum();

System.out.println(answer);

prints

145

CodePudding user response:

You have to do a mapToInt() with e.getA() returning an Integer followed by sum()

Integer sumOfA = someObj.someList().stream()
    .filter(e -> e != null && e.getB() == 6 && e.getC == 0)
    .mapToInt(e::getA).sum();

CodePudding user response:

Assuming the Elements in A are Strings you could use regular expressions to remove Letters from the value. The Expression for a non-digit Charakter ist \D. The regex can be applied by using .map(). The complete answer would then look like.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

Pattern reg = Pattern.compile("\d ");
int result = someObj.someList()
                    .stream()
                    .filter(e -> e != 
                        null && e.getB() == 6 && e.getC == 0)
                    .map(s -> 
                        Integer.parseInt(s.getA().repalceAll("[\\D]","")))
                    
                    .mapToInt(Integer::intValue)
                    .sum()
  • Related