Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulate output in java8 stream

Imagine we have list of 3 objects with minutes field as values: 5,5,7, 8

int sumOfFields = found.stream()
        .filter(abc -> minutesLessThan5(abc.getMinutes())))
        .mapToInt(abc::getMinutes)
        .sum();

// will return 10

But how can I change my output e.g. instead of getMinutes I want to return my own value e.g. 40

int sumOfFields = found.stream()
        .filter(abc -> minutesLessThan5(abc.getMinutes())))
        .mapToInt(abc ->abc.getMinutes() = 40)  //this is pseudo code what I try to achive
        .sum();

// output should be 80.
like image 449
degath Avatar asked Dec 18 '25 15:12

degath


1 Answers

Not really sure why people didn't made an answer to this, yet as pointed out in comments, you can follow either of the approach

int sumOfFields = found.stream()
        .filter(abc -> minutesLessThan5(abc.getMinutes())))
        .mapToInt(abc -> 40) // map value to be returned as 40 
        .sum();

or instead since you are replacing all such values with a constant value 40, you can also make use of the count() and multiply that with the constant value.

int sumOfFields = (int) found.stream() // casting from long to int
        .filter(abc -> minutesLessThan5(abc.getMinutes())))
        .count() * 40;
like image 80
Naman Avatar answered Dec 20 '25 03:12

Naman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!