Thursday, March 20, 2014

Java 8 Lambda Expressions Example

Finally Oracle officially presented Java 8. A key feature of Java 8 - Support for lambda expressions that allow developers to effectively apply the simultaneous computation and callback functions in programming, especially in the popular cloud applications. Function can be treated as method arguments, and code as data, which makes the final results more compact. 

Java Lambda syntax is pretty similar to what we know in C#. 
Let's see.

Starting a new Thread:

new Thread(() -> { System.out.println("Java 8 Lambda"); }).start();

Working with Collections:

List<Employee> employees = new ArrayList<>();
     employees.add(new Employee("John"));
     employees.add(new Employee("Robert"));
     employees.add(new Employee("Anna"));


employees.forEach(e -> e.setAge(35));


List<Employee> filtered =
                (f -> f.getName().equals("Anna") || f.getName().equals("John"))

Optional<Employee> findFirst =
                .filter(e -> e.getName().equals("Anna")).findFirst();


List<Employee> list =
                .filter(p -> p.getAge() > 18).collect(Collectors.toList());

Happy codding friends! :)

No comments:

Post a Comment