Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Java 8 Lambda Expressions in Java 7 or Older

DZone's Guide to

Using Java 8 Lambda Expressions in Java 7 or Older

· Java Zone
Free Resource

Never build auth again! The Okta Developer Platform makes it simple to implement authentication, authorization, MFA and more in Java applications. Get started with the free API.

I think nobody declines the usefulness of Lambda expressions, introduced by Java 8. However, many projects are stuck with Java 7 or even older versions. Upgrading can be time consuming and costly. If third party components are incompatible with Java 8 upgrading might not be possible at all.
Besides that, the whole Android platform is stuck on Java 6 and 7. 

Nevertheless, there is still hope for Lambda expressions!

Retrolambda provides a backport of Lambda expressions for Java 5, 6 and 7.

From the Retrolambda documentation:

Retrolambda lets you run Java 8 code with lambda expressions and method references on Java 7 or lower. It does this by transforming your Java 8 compiled bytecode so that it can run on a Java 7 runtime. After the transformation they are just a bunch of normal .class files, without any additional runtime dependencies.


To get Retrolambda running, you can use the Maven or Gradle plugin.

If you want to use Lambda expressions on Android, you only have to add the following lines to your gradle build files:

<project>/build.gradle:

buildscript {
  dependencies {
    classpath 'me.tatarka:gradle-retrolambda:2.4.0'    
  }
}

<project>/app/build.gradle:

apply plugin: 'com.android.application'
 
// Apply retro lambda plugin after the Android plugin
apply plugin: 'retrolambda' 
 
android {
  compileOptions {
    // change compatibility to Java 8 to get Java 8 IDE support  
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}


Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Published at DZone with permission of Michael Scharhag, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}