Manipulates output in a java8 stream… here is a solution to the problem.
Manipulates output in a java8 stream
Suppose we have a list of 3 objects with values in the minute field as: 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
For example, instead of getMinutes, I want to return my own value, such as 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.
Solution
Not quite sure why people aren’t answering this, but as noted in the comments, you can go either way
int sumOfFields = found.stream()
.filter(abc -> minutesLessThan5(abc.getMinutes())))
.mapToInt(abc -> 40) // map value to be returned as 40
.sum();
Or since you want to replace all such values with a constant value of 40
, you can also use count()
and multiply it by the constant value.
int sumOfFields = (int) found.stream() // casting from long to int
.filter(abc -> minutesLessThan5(abc.getMinutes())))
.count() * 40;