19 April 2014

Java 8 features

Hello folks,

I am very glad that java 8 is now released...

It contains many features among them are ... "Lambda expressions", "java.util.stream" and "java.time" packages.

See more here (java 8 release notes) ....

Both Lambda expressions and java.util.stream will provide a very good experience and make the Java language more modern (I believe if such decision not talked, many ppl would migrate to more modern langs like Scala).

And "java.time" is very straight forward api... see it here

I've tried java8 in Eclipse kepler, but it needed some patch to support java8 syntax

The following example illustrates Lambda expressions along with java.util.stream..

package helloJava8;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static void main(String[] args) {

        List<Employee> list = new ArrayList<>();

        list.add(new Employee("Ali", 20, 2000));
        list.add(new Employee("Wael", 30, 3000));
        list.add(new Employee("Taher", 40, 1000));
        list.add(new Employee("Ibrahim", 10, 1500));

        System.out.println("Sorted:");
        list.stream().sorted((o1, o2) -> o1.getName().compareTo(o2.getName()))
                .forEach(o -> System.out.println(o));

        System.out.println("\nFiltered: (age >= 30) ");
        list.stream().filter(o -> o.getAge() >= 30).forEach(o -> System.out.println(o));

        System.out.println("\nMapping user to its salary then sort:");
        list.stream().map(o -> o.getSalary()).sorted().forEach(o -> System.out.println(o));
    }

    static class Employee {
        private String name;
        private int age;
        private int salary;

        public Employee(String name, int age, int salary) {
            super();
            this.name = name;
            this.age = age;
            this.salary = salary;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        public int getSalary() {
            return salary;
        }

        public void setSalary(int salary) {
            this.salary = salary;
        }

        @Override
        public String toString() {
            return "Employee [name=" + name + ", age=" + age + ", salary=" + salary + "]";
        }
    }
}


You have to read more about lambda and streams here:
http://docs.oracle.com/javase/tutorial/java/javaOO/lambdaexpressions.html
http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html


That's all.
Post a Comment