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

Viewed 25773

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++;
                    }
                });
4 Answers

You can use AtomicInteger, and incrementAndGet method on it.

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

and incrementing position[0]++;

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++);
        });
    }
}

I think you senior is asking you to use streams for collections. Then use collection.stream.filter.count based on your logic that will produce a long as the value and use it.

I know it is late, so I will just put it out here for future seekers. Here is how you can do it in a very simple way :

use indexOf(Object O) property of collections

StringBuffer messageBody = new StringBuffer();    
List<VipObj> listOfAllVips = getResponse();
    listOfAllVipsLocal.forEach(vip -> {
                            messageBody.append("\n\t" + (listOfAllVipsLocal.indexOf(vip) + 1) + ". " + vip.getBaseUrl() + "\n");
                        });
Related