Search code examples
javaeclipsepriority-queue

Java + Eclipse: The method computeIfAbsent(String, (<no type> k) -> {}) is undefined for the type


I am using Eclipse (Mars.1 Release (4.5.1)) and encountering the following error: The method putIfAbsent(String, new PriorityQueue<>()) is undefined for the type Map<String,PriorityQueue<String>>. Everything seems done correctly but still getting the error. What could I be missing?

Map<String, PriorityQueue<String>> targets = new HashMap<>();

...


for(String[] ticket: tickets) {
    targets.putIfAbsent(ticket[0], new PriorityQueue<>());
}

EDIT Did the following, yet still getting the error

enter image description here

enter image description here

EDIT 2

Added Java 8 SE, yet still getting the error.

enter image description here

enter image description here

enter image description here

EDIT 3

enter image description here


Solution

  • There's no method Map#putIfAbsent(K key, V value) in Java 7, but there's in Java 8. See:

    In your specific case, make sure the project properties under Eclipse (described below) are set to Java 8. You can edit them by doing: Right click on project > Properties:

    • Project properties > Java Build Path
    • Project properties > Java Comiler

    Here's a possible solution:

    Java Build Path

    If your Java Build Path is targeted to Java 7, follow the below steps to change it:

    • Select JRE System Library
    • Click button Edit... located on the right side
    • Use one of the following options
      • Global: Workspace default JRE. Make sure it is set to Java 8
      • Local: Alternate JRE. Choose Java 8.

    After setting this, you can continue to check the Java Complier.

    Java Complier - project settings Java Complier - Eclipse settings

    Now, you should run your project without problem.


    Do I have to do this to each project individually or does it apply to all projects?

    You don't have to do this for each project. You can have a set-up for all projects of this workspace.

    To setup Java Runtime Environments for all the projects, you can check which JREs are installed and change the default one.

    • Go to Eclipse > Preferences...
    • Search JRE
    • Check the installed JREs
      • If your recently installed JREs aren't appeared, then add them manually one by one using button Add.... Or add them automatically using the button Search....
      • Select the default JRE that you want

    As the screenshot shown: By default, the checked JRE is added to the build path of newly created Java projects. Now it should be OK for all the projects.

    Installed JREs

    To edit the JRE for a specific project, you can. Here're the steps to do it:

    • Select the target project, right click > Properties
    • Select Java Build Path
    • Edit JRE System Library
    • Choose your preferred JRE version from
      • Execution Environment
      • Alternate JRE
      • Workspace default JRE