Picking from a list of individuals based on their fitness values I have this method that takes a list of my individuals (class has public field fitnessValue). I sum all fitnessValue and then draw a random value between 0 and sum of fitnessValue. In the end, I check for each individual where cumulative sum of fitnessValue passes the point I counted before and return the one which passed first. 

public Individual pickRandomIndividual(List&lt;Individual&gt; pool) {
    Double totalScore = 0d;
    Double runningScore = 0d;
    for (Individual ind : pool) {
        totalScore += ind.fitnessValue;
    }

    Double rnd = Math.random() * totalScore;

    for (Individual ind : pool) {
        if (rnd &gt;= runningScore &amp;&amp;
                rnd &lt;= runningScore + ind.fitnessValue) {
            return ind;
        }
        runningScore += ind.fitnessValue;
    }
    return null;
}  


I want to refactor this function with Java 8 streams. Any idea how can I achieve that?

I changed it a bit, into:

Double fitnessSum = genePool.stream()
                .mapToDouble(individual -&gt; individual.fitnessValue)
                .sum();
Double runningScore = 0d;

Double rnd = random() * fitnessSum;

for (Individual g : genePool) {
    if (rnd &gt;= runningScore &amp;&amp; rnd &lt;= runningScore + g.fitnessValue) {
            return g;
    }
    runningScore += g.fitnessValue;
}
return null;


Still, I do not know how to change cumulative sum part into a stream. Maybe entire logic is poorly implemented? I just want to draw one Individual from the list depending on how large the Individual's fitnessValue is.
You have to keep in mind that Streams are not the solution to everything. In this case for example, you need to keep track of multiple values, i.e. the current individual, and a cumulative sum (and you have to return a a value as soon as a certain condition is met). Yes, there are ways to do this with Streams, but I think in this case it is best to implement it with a simple loop like you have.

A couple of side notes:


Use the primitive type double instead of the wrapper class.
Declare variables as late as possible.
Perhaps allow the user to pass a Random instance.
I think your implementation can be simplified by subtracting, which would then mean you only have to check for &lt; 0, e.g.:

double fitnessSum = genePool.stream()
        .mapToDouble(individual -&gt; individual.fitnessValue)
        .sum();

double remainder = Math.random() * fitnessSum;
for (Individual gene : genePool) {
    remainder -= gene.fitnessValue;
    if (remainder &lt;= 0.0) {
        return gene;
    }
}
return genePool.get(genePool.size() - 1);