Turn a for into lambda with variable interaction

Asked

Viewed 587 times

1

How to turn the section below into a Lambda code?

The idea is to multiply the maxScore for i so that at each interaction it increases the number, only for the first 5 results.

    for(int i=0;i<5;i++){
        list.get(i).setScore(maxScore + (0.01d * i));
    }

The idea of the code is more or less this:

    List<HashObject> list = createObjects(10);
    Double maxScore = 0.9d;

    for(int i=0;i<5;i++){
        list.get(i).setScore(maxScore + (0.01d * i));
    }

Hashobject class:

    public class HashObject {
        private Integer id;
        private String name;
        private Double score;

        /* Getters and Setters */
    }

2 answers

1


Sirs,

I solved the problem with the command:

IntStream.range(0,5).forEach(p -> list.get(p).setScore(0.01d * (double)p));

Where the command Intstream.range(0,5) loops, foreach I walked the loop and the p is the interaction of the loop (the i in the case of).

0

  • Bruno, the quality of the answer can surely be improved! Exemplify with an application that can be executed or something like..

  • Only the foreach does not serve, because I need that the value inside score is incremented for each interaction of Loop.Ex.: when i is equal to 0 it will not add anything to maxScore, when i is equal to 1 it has to add 0.01 in maxScore, when i is equal to 2 it has to add 0,02 no max score.

  • I need to do exactly the same thing that this loop would do only with lambda

Browser other questions tagged

You are not signed in. Login or sign up in order to post.