📜 ⬆️ ⬇️

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<Integer> cmp = (x, y) -> (x < y) ? -1 : (x > y) ? 1 : 0; 

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

This design replaces the bulky code:
')
 Comparator<Integer> comparator = new Comparator<Integer> () { 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 (see below). Also add a bunch of useful interfaces like Factory.make, Mapper.map. Well, and many more flexible uses and applications.

It is also possible, instead of a manual description of a lambda, to take its implementation from other classes:
 Comparator<Integer> comparator = LibraryComparator::compare; //     


Expansion of interfaces by default methods (defender)


Yes, now the interface methods are divided into abstract (no implementation) and non-abstract (default), which have a certain 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 a 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 makes working with collections much more flexible. 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 placed this value (s) in another list.

Learn more about new features: http://openjdk.java.net/projects/lambda/

About new meetings: http://jug.ru/
Recorded video, I will be glad if someone brings a link to it to the public.

Source: https://habr.com/ru/post/155191/


All Articles