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

I have the following problem. I have an integer position that starts at 1 and increases every time a particular person from txt is in a certain position in xml. If I use the classic iteration with foreach for (PersonMatchInfo pmi : personMatchInfo) , this works, but my older one asked me to do foreach with Java 8, and this type of iteration only works with final variables. How can I increment an integer in a new Java 8 loop? Thanks.

 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++; } }); 
+5
source share
3 answers

You can use AtomicInteger and incrementAndGet .

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

and incrementing position[0]++;

+8
source

I think you, senior, ask you to use streams for collections. Then use the collection.stream.filter.count file based on your logic, which will give a long result and use it.

0
source

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

Source: https://habr.com/ru/post/1272274/


All Articles