SnG
SnG

Reputation: 402

Sum elements in stream while taking max (0,x)?

Suppose I have a List<Double> such as [2,4.3,-1.1]. I want to sum these elements, while removing all of the negative numbers (I'm thinking to take the max of each number vs 0). For this example, the answer should be 2 + 4.3 = 6.3

I want to use Java 8 streams to do this, but I'm stuck in getting the max (x,0) part down. Does anyone have any clue to do this?

This is what I have so far:

scores.stream()
      .mapToDouble(i -> i.getValue())
      // max between the number and 0??
      .sum

Upvotes: 2

Views: 188

Answers (1)

Alex - GlassEditor.com
Alex - GlassEditor.com

Reputation: 15507

.mapToDouble(i -> Math.max(i, 0))

You could also do this with a filter:

.filter(i -> i > 0)

Upvotes: 4

Related Questions