LearnFrenzy
Sign in Take a free test

HashMap and TreeMap · Find the Error · Question 9

Error: computeIfAbsent returning the wrong type Answer, explanation & discussion

  • Find the error
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

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

Main.java
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        Map<String, List<Integer>> scores = new HashMap<>();
        scores.computeIfAbsent("Asha", k -> 0).add(90);
        System.out.println(scores);
    }
}
  • A add cannot take 90
  • B The mapping function must produce the value type List<Integer>, but it returns 0; write k -> new ArrayList<>() Correct
  • C computeIfAbsent needs three arguments
  • D scores must be a TreeMap
Correct Answer: Option B

javac reports an incompatible type in the lambda's return 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