Explain Codes LogoExplain Codes Logo

Java "lambda expressions not supported at this language level"

java
java-8
lambda
build-tools
Alex KataevbyAlex Kataev·Aug 24, 2024
TLDR

Resolving the "lambda expressions not supported at this language level" error involves updating your Java version to least Java 8. Verify that your IDE's compiler settings and build tools like Maven or Gradle are compatible with Java 8+.

In IntelliJ IDEA:

  1. Navigate to File > Project Structure
  2. Ensure Project SDK is set to Java 1.8+
  3. Align the Language level to 8+

For Eclipse:

  1. Go to Project Properties > Java Compiler.
  2. Check Enable project specific settings
  3. Set the Compiler compliance level to 1.8+

The correct setup will allow you to compile this lambda expression:

Arrays.asList("a", "b").forEach(e -> System.out.println(e + " carpet rides!")); // here's your magic carpet ride!

In your Maven pom.xml file:

<properties> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties>

In your Gradle build.gradle file:

sourceCompatibility = '1.8' targetCompatibility = '1.8'

For users of Gradle, Maven and other build tools, correctly configuring your version specifications is vital for Java 8 support. Remember to re-synchronize your project after modifying the build scripts.

In Android Studio, ensure that your build.gradle file in the app module specifies Java 8 compatibility:

android { compileOptions { sourceCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8 } }

Guarding against common pitfalls

Keep in mind that common issues may include:

  • Utilizing an unsupported version of IntelliJ IDEA or Eclipse for Java 8.
  • Not updating the JDK path in the IDE after installing an updated Java version.

Ensure your system's installed JDK version and your IDE's compiler settings are in sync.

Troubleshooting tips and tricks

If you are still dealing with trouble, here are a few tips to diagnose:

  • Re-import your project.
  • Invalidate caches and restart the IDE: File > Invalidate Caches/Restart in IntelliJ IDEA.
  • Double-check environment variables like JAVA_HOME for correct Java version pointers.

Embracing Java 8 Features

With Java 8, you can now tap into entire spectrums of features like streams, method references, and a lot apart from lambda expressions.

Soaking up these features helps write concise and expressive code, enabling you to churn out elegant and efficient solutions.

Eclipse users can leverage Quick Fix (Ctrl + 1) tool, which can lead the way to necessary changes for upgrading the language level compatibility.

Also, revisit the Execution Environment under Java Compiler settings in Eclipse to ensure it relates to a compatible Java SE 8 environment.