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"));


Iteration:


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


Filter:


List<Employee> filtered = employees.stream().parallel().filter
                (f -> f.getName().equals("Anna") || f.getName().equals("John"))
                .collect(Collectors.toList());

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

Parallelism:


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

Happy codding friends! :)

No comments:

Post a Comment