Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment a "number" in a Java 8 lambda expression in a loop?

Tags:

java

I have the following problem. I have an integer position which starts at 1 and increments every time a specific person from a txt is found at a specific position in an xml. If I use the classic iteration with the foreach for (PersonMatchInfo pmi : personMatchInfo) it works, but my senior asked me to do with the Java 8 foreach and this type of iteration works only with final variables. How can I increment the integer in the new Java 8 loop? Thank you.

int position = 1;
personMatchInfo.forEach(pmi ->{

                    if (!stopwatch1.isStarted()) {
                        stopwatch1.start();
                    } else if (stopwatch1.isStarted()) {

                    }

                    if (pmi.getPersonName().equals(e.getValue())) {

                        positionMap.put(position, positionMap.get(position) + 1);
                        break;

                    } else {

                        position++;
                    }
                });
like image 854
Tayfun Omer Avatar asked Oct 02 '17 08:10

Tayfun Omer


People also ask

Can we increment a variable inside forEach lambda?

Let's say, we have a list of integers and we want to know the number of integers that are greater than 50 using a forEach loop and lambda expression. We can not declare an integer variable and increment it inside the loop after checking the color or each ball since it will be an error.

Can we change the lambda expression variable data?

Yes, you can modify local variables from inside lambdas (in the way shown by the other answers), but you should not do it.


2 Answers

You can use AtomicInteger, and incrementAndGet method on it.

Other solution would be int[] position = new int[]{1};

and incrementing position[0]++;

like image 178
mlecz Avatar answered Sep 18 '22 20:09

mlecz


You can use a static variable :

public class Poubelle {

    private static int position = 1;

    public static void setPosition (List<PersonMatchInfo> listPersonMatchInfo) {

          listPersonMatchInfo.forEach(pmi -> {
          pmi.setPosition(position++);
        });
    }
}
like image 38
Nicolas Avatar answered Sep 17 '22 20:09

Nicolas