LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Find the Error · Question 6

Error: Map.forEach with a one-parameter lambda Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

The program below does not compile. Which statement correctly describes the problem?

Main.java
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = Map.of("pen", 10, "ink", 4);
        stock.forEach(item -> System.out.println(item));
    }
}
  • A Map.of maps cannot be iterated
  • B Map.forEach takes a BiConsumer, so the lambda needs two parameters: (item, qty) -> … Correct
  • C println cannot be used in a lambda
  • D forEach must return a value
Correct Answer: Option B

Iterable.forEach takes one parameter; Map.forEach takes key and value.

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!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links