How can I assign values to variables with lambdas without the variables being final?

Viewed 28
int points = 0;

tournaments.stream().filter(t -> t.getYear() == lastTournament.get().getYear())
                    .forEach(t -> points = t.getResult(player).get());

I have a list of tennis tournaments, what I'm trying to extract is the amount of points a player scored in all the tournaments that took place in the lastTournament's year, a player might not have played in a certain tournament which is why the scores are optionals.

I'm trying to understand how I can do this with a lambda because it looks neater and is easier to write than a for loop, problem is that with points not being declared as final I incur in

"Local variable points defined in an enclosing scope must be final or effectively final"

I understand the error, what I'd like to know is if there's another way for me to do what I'm trying to do with a lambda and/or if I'm looking at the problem the wrong way and lambdas/streams are not the tool I should be using.

1 Answers

You want to sum all of scores for the player and make that the result of your stream operations. Something like this:

points = tournaments.stream()
        .filter(t -> t.getYear() == lastTournament.get().getYear()) // I'm assuming this .get() is always present
        .mapToInt(t -> t.getResult(player).orElse(0))
        .sum();
Related