英文:
How to increment count within foreach loop
问题
public static void main(String[] args) {
int count = 0;
List<String> namesList = new ArrayList<>();
namesList.add("gaurav");
namesList.add("deepak");
namesList.add("anit");
namesList.add("garvit");
namesList.add("satvir");
namesList.add("lino");
namesList.add("gogo");
namesList.forEach(names -> {
if (names.startsWith("g")) {
count++;
}
});
if (count > 1) {
System.out.println("executed");
}
}
在增加计数时遇到以下错误:
在封闭范围中定义的局部变量 "count" 必须是 final 或者是 effectively final
英文:
Below is my code:
public static void main(String[] args) {
int count = 0;
List<String> namesList = new ArrayList<>();
namesList.add("gaurav");
namesList.add("deepak");
namesList.add("anit");
namesList.add("garvit");
namesList.add("satvir");
namesList.add("lino");
namesList.add("gogo");
namesList.forEach(names -> {
if (names.startsWith("g")) {
count++;
}
});
if (count > 1) {
System.out.println("executed");
}
}
Getting the below error while incrementing count:
Local variable count defined in an enclosing scope must be final or effectively final
答案1
得分: 1
不要增加一个变量。
long count = namesList.stream()
.filter(name -> name.startsWith("g"))
.count();
这样更易于阅读和理解,而且代码更简洁。
英文:
Don't increment a variable.
long count = namesList.stream()
.filter(name -> name.startsWith("g"))
.count();
It's eaisier to read and understand, and it's less code.
答案2
得分: 0
使用 AtomicInteger
进行如下操作:
AtomicInteger count = new AtomicInteger();
namesList.forEach(names -> {
if (names.startsWith("g")) {
count.getAndIncrement();
}
});
if (count.get() > 1) {
System.out.println("executed");
}
或者使用 Stream API 进行如下操作:
long count = namesList.stream()
.filter(name -> name.startsWith("g")) // 使用条件进行过滤
.count(); // 然后计数
英文:
Use AtomicInteger
for this
AtomicInteger count = new AtomicInteger();
namesList.forEach(names -> {
if (names.startsWith("g")) {
count.getAndIncrement();
}
});
if(count.get() > 1) {
System.out.println("executed");
}
Or using Stream API
long count = namesList.stream()
.filter(name -> name.startsWith("g")) // filter with condition
.count(); // then count
答案3
得分: 0
你也可以使用流来实现这个。使用 filter()
来查找以 g
开头的名称,使用 findFirst()
来找到第一个。如果没有符合条件的,将返回 null
。
String result = namesList
.stream()
.filter(name -> name.startsWith("g"))
.findFirst()
.orElse(null);
英文:
You can do that with a stream as well. Use filter()
to find the names starting with g
, use findFirst()
, to find the first one. If there is none, this will return null
.
String result = namesList
.stream()
.filter(name -> name.startsWith("g"))
.findFirst()
.orElse(null);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论