Question 9
Back to Exercise
The program below does not compile. Which statement correctly describes the problem?
import java.util.List;
public class Main {
public static void main(String[] args) {
int total = 0;
List.of(1, 2, 3).forEach(n -> total += n);
System.out.println(total);
}
}
- A forEach needs a Consumer class
- B A lambda can only use final or effectively final local variables, and total is modified; use a stream sum() or an AtomicInteger Correct
- C List.of is immutable
- D n must be declared int
Correct Answer: Option B
Write int total = List.of(1, 2, 3).stream().mapToInt(Integer::intValue).sum();
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!