java 8 lambda code example

Example 1: how to use lambda in java

StateOwner stateOwner = new StateOwner();

stateOwner.addStateListener(
    (oldState, newState) -> System.out.println("State changed")
);

Example 2: lambda expression java

public class TestLambda {

   public static void main(String args[]) {
      List<String> lowerCaseStringsList = Arrays.asList("a","b","c");
     // the :: notation is the lambda expression
     // it's the same as the anonymous function s -> s.toUpperCase()
      List<String> upperCaseStringsList = lowerCaseStringsList.stream().
        map(String::toUpperCase).
        collect(Collectors.toList());
   }   
}

Example 3: lambda java advanced condition

public void method() {    String localVariable = "Local";    Foo foo = parameter -> {        String localVariable = parameter;        return localVariable;    };}

Tags:

Java Example