KevinVerleysen
KevinVerleysen

Reputation: 27

Use setter methods while iterating over collections using lambdas

This might seem a simple question, but I have been getting stuck on this little problem I have.

In java 7 you can iterate over your objects and set new values to its attribute.

for (int i = 0; i < continentLijst.size(); i++) {
        continentLijst.get(i).setContinentId(i);
}

Now I'm searching to do the same in a Java 8 lambda. I thought something like:

 int i =0;

 continentLijst.stream().forEach(e -> {

        e.setContinentId(i++);
  });

Which obviously gives an error... As I said this might be a beginners mistake I'm making, but any help would be awesome!

Upvotes: 0

Views: 3334

Answers (1)

Alexis C.
Alexis C.

Reputation: 93842

Your attempt doesn't work because a variable used in a lambda expression must be (effectively) final (and you are trying to update the value of iin the lambda expression).

You could hold a reference to a counter (such as an AtomicInteger)

AtomicInteger counter = new AtomicInteger(0);
continentLijst.forEach(c -> c.setContinentId(counter.getAndIncrement()));

or use an IntStream to generate a stream of corresponding indexes:

IntStream.range(0, continentLijst.size())
         .forEach(i -> continentLijst.get(i).setContinentId(i));

Upvotes: 6

Related Questions