如何在循环中增加 Java 8 lambda 表达式中的“数字”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46522136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to increment a "number" in a Java 8 lambda expression in a loop?
提问by Tayfun Omer
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.
我有以下问题。我有一个整数位置,它从 1 开始,每次在 xml 中的特定位置找到来自 txt 的特定人时都会递增。如果我将经典迭代与 foreach 一起使用for (PersonMatchInfo pmi : personMatchInfo)
它可以工作,但是我的前辈要求我使用 Java 8foreach
并且这种类型的迭代仅适用于最终变量。如何在新的 Java 8 循环中增加整数?谢谢你。
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++;
}
});
回答by mlecz
You can use AtomicInteger
, and incrementAndGet
method on it.
您可以在其上使用AtomicInteger
, 和incrementAndGet
方法。
Other solution would be int[] position = new int[]{1};
其他解决方案是 int[] position = new int[]{1};
and incrementing position[0]++;
和 incrementing position[0]++;
回答by Nicolas
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++);
});
}
}
回答by Mark_ZuckerBerg
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.
我认为您的前辈要求您使用流进行集合。然后根据您的逻辑使用 collection.stream.filter.count ,该逻辑将产生一个 long 作为值并使用它。