JSR 335 or lambda expressions in JAVA 8

    Introduction


    I attended yesterday a seminar on lambda expressions in JAVA 8. They told a lot of interesting things.

    Of the interesting things:

    lambda expressions


    Comparator cmp = (x, y) -> (x < y) ? -1 : (x > y) ? 1 : 0;
    

    On the left is the required interface that defines lambda. Right expression. The left side of "->" is the signature, the right is the implementation.

    This construction replaces cumbersome code:

    Comparator comparator = new Comparator () {
      public int compare(Integer x, Integer y) {
        return (x < y) ? -1 : (x > y) ? 1 : 0;
      }
    };
    

    lambda expressions can implement any functional interface. A functional interface is an interface with one abstract method (more on that below). A bunch of useful interfaces like Factory.make, Mapper.map will also be added. Well and many more flexible possibilities of use and application.

    It is also possible to take its implementation from other classes instead of manually describing the lambda:
    Comparator comparator = LibraryComparator::compare; // Некая реализация из библиотеки
    


    Extending interfaces with default methods (defender)


    Yes, now the interface methods are divided into abstract (have no implementation) and not abstract (default), which have some default implementation. This innovation is recognized to simplify the expansion of the interfaces of the basic JAVA entities, and indeed any interfaces with compatibility support. For example, there is an old interface:
    public interface OldInterface {
        void method();
      }
    

    We need to expand it, but for the old code to continue to work. Add the default method:
    public interface OldInterface {
        void method();
        void newMethod() default {
          // default implementation
        }
      }
    

    To write or not to write the word default in interfaces is discussed.

    Stream (bulk) operations


    A cool thing that allows you to work with collections much more flexibly. For example, an abstract example in a vacuum:
    list.stream().parallel().reduce(Math::max).into(newList);
    

    We tried to sort the collection in parallel with the specified comparator (maybe lambda), then we filtered the maximum element and put this value (s) in another list.

    More information about the new chips: http://openjdk.java.net/projects/lambda/

    About new meetings: http://jug.ru/ We
    recorded the video, I will be glad if anyone gives a link to it for the public.

    Also popular now: