Accessing Class Variables from a Lambda Expression - Java Lambda Stream

Java examples for Lambda Stream:Lambda

Introduction

Use of instance variables contained in enclosing classes from within lambda expressions.

Demo Code

import java.util.function.Consumer;

public class Main {
  String CLASSA = "Class-level A";

  class InnerClass {
    public String CLASSA = "Class-level B";
    void lambdaInMethod(String passedIn) {
      String METHODA = "Method-level A";
      // passedIn = "test";
      Consumer<String> l1 = x -> {
        System.out.println(x);//from  w w  w  .  ja va  2  s  .c o m
        System.out.println("CLASSA Value: " + CLASSA);
        System.out.println("METHODA Value: " + METHODA);
      };
      l1.accept(CLASSA);
      l1.accept(passedIn);
    }
  }
}

Related Tutorials