Java 8 new features

Source: Internet
Author: User
Tags stream api

Java 8 new features

Content:
1. lambda expressions
2. streamAPI
3. built-in function Interfaces
4. default Interface Implementation Method
5. Use lambda/streamAPI in android

========

1. lambda expressions:
Several forms:

()->statement()->(statement)()->{statement}

Take Thread as an example:

new Thread(new Runnable(){   public void run(){    }}).start();new Thread(()->{     System.out.println(Thread.currentThread().getName());}).start();

For example:

Collections.sort(list, (x, y) -> y - x);

Lambda expressions simplify the writing of anonymous internal classes. It requires only one abstract method in the anonymous internal class, which is also called a function interface. If the abstract method has multiple parameters, you can write as follows:

(arg1,arg2)->{}(int arg1,double arg2)->{}

Both methods are acceptable.
Lambda is similar to an anonymous internal class. It can access local final variables in the external region, as well as member variables and static variables.

@ FunctionalInterfaceinterface Converter
  
   
{T convert (F from);} final int num = 1; Converter
   
    
StringConverter = (from)-> String. valueOf (from + num); stringConverter. convert (2); // 3 // But unlike an anonymous object, the variable num does not need to be final. Int num = 1; Converter
    
     
StringConverter = (from)-> String. valueOf (from + num); stringConverter. convert (2); // 3 // num is implicitly treated as a final variable during compilation. The following code is incorrect: int num = 1; Converter
     
      
StringConverter = (from)-> String. valueOf (from + num); num = 3;
     
    
   
  

2. function interface:
A functional interface contains only one abstract method. In addition to using standard methods in Java to create implementation objects, you can also use lambda expressions to create implementation objects. This greatly simplifies the implementation of the Code. When using lambda expressions, you only need to provide formal parameters and method bodies. Since function interfaces have only one abstract method, the method body declared through lambda expressions must be the only abstract method implementation, the type of the formal parameter can be automatically inferred based on the Type Declaration of the method.

3. built-in function interfaces:
Java 8 APIS also provide many new functional interfaces to reduce the workload of programmers.

Predicates
Predicate is a Boolean function with only one input parameter. The Predicate Interface contains multiple default methods for processing complex logical verbs (and, or, negate)

Private static void testPredicate (List
  
   
List, Predicate
   
    
P) {list. stream (). filter (p). forEach (arg-> {System. out. println (arg) ;}// client calls List
    
     
L = Arrays. asList (aaa, hhaha, hiahia, hehe); testPredicate (l, (arg)-> arg. length () = 3 );
    
   
  

The function of the testPredicate method is to filter elements in the list set by using the rules specified by predicate, and finally print the elements that pass the filtering. Of course, you can use the lambda expression (arg)-> arg. length = 3, meaning that the filter condition is that the element size is 3. Of course, Predicate can have multiple conditions:

Predicate
  
    p1 = (arg)->arg.charAt(0)=='h';    Predicate
   
     p2 = (arg)->arg.length()<6;    testPredicate(l,p1.and(p2));
   
  

For the principle, refer to the Predicate source code:

@FunctionalInterfacepublic interface Predicate
  
    {    boolean test(T t);    default Predicate
   
     and(Predicate
     other) {        Objects.requireNonNull(other);        return (t) -> test(t) && other.test(t);    }    default Predicate
    
      negate() {        return (t) -> !test(t);    }    default Predicate
     
       or(Predicate
       other) {        Objects.requireNonNull(other);        return (t) -> test(t) || other.test(t);    }    static 
      
        Predicate
       
         isEqual(Object targetRef) { return (null == targetRef) ? Objects::isNull : object -> targetRef.equals(object); }}
       
      
     
    
   
  

As you can see, Predicate is actually a function interface. Negate/and/or is its default method.

Functions
The Function interface receives a parameter and returns a single result. By default, multiple functions can be chained together (compse, andThen)

String s = abcdefg;Function
  
    f = arg->arg.substring(3);System.out.println(f.apply(s));//defg
  

For example:

String s = abcdefg; Function
  
   
F = arg-> arg. substring (3); Function
   
    
F2 = f. andThen (arg-> (arg. length (); System. out. println (f2.apply (s); // output 4
   
  

Calculate f First, return arg. substring (3), and then execute arg. length () on the returned String, so the result should be 4.

Reference source code:

@FunctionalInterfacepublic interface Function
  
    {    R apply(T t);    default 
   
     Function
    
      compose(Function
      before) {        Objects.requireNonNull(before);        return (V v) -> apply(before.apply(v));    }    default 
     
       Function
      
        andThen(Function
        after) { Objects.requireNonNull(after); return (T t) -> after.apply(apply(t)); } static 
       
         Function
        
          identity() { return t -> t; }}
        
       
      
     
    
   
  

Supplier:
The Supplier interface generates a result of a given type. Unlike Function, Supplier does not input parameters.
For example, construct an object:

Supplier
  
    s = ()->new Person();s.get().sayHello();static class Person{        public void sayHello(){            System.out.println(hello);        }}
  

Reference source code:

@FunctionalInterfacepublic interface Supplier
  
    {    /**     * Gets a result.     *     * @return a result     */    T get();}
  

Consumers:
Consumer indicates the operation to be performed on an input parameter.
For example:

private static void testConsumer(List
  
    l,Consumer
   
     consumer){        l.stream().forEach(i->{            consumer.accept(i);        });    }testConsumer(Arrays.asList(1222,12,9),i->{System.out.println(hello:+i);});
   
  

BiConsumer:
Similar to Consumer, but two parameters are accepted. A common scenario is Map traversal.
Map foreach traversal:

Map
  
    map = new HashMap<>();map.put(aa, value1);map.put(bb, value2);map.put(cc, value3);map.forEach((arg1,arg2)->{    System.out.println(arg1+,+arg2);});
  

4. Stream API:
Java. util. Stream represents the sequence of a certain element, and various operations can be performed on these elements. Stream operations can be intermediate operations or end operations. The end operation will return a certain type of value, and the intermediate operation will return the stream object itself. You can call the same stream operation method multiple times to concatenate the operation result. Stream is created based on a source, such as list or set in java. util. Collection (map cannot be used as the source of Stream ). Stream operations can be executed in sequence or in parallel.
Common Operations: filter/sorted/map/match/count/reduce/
For example, create a set:

List
  
    l = Arrays.asList(aaa,hhaha,hiahia,hehe);
  

Filter: filter specific elements (return stream)

Object[] l1 = l.stream().filter(arg->{    return arg.length()>3;}).toArray();for(int i = 0; i
  

Map: Execute an operation on each element: (return stream)

Object[] l2 = l.stream().map(arg1->arg1.toUpperCase()).toArray();for(int i = 0; i 

Sorted: Sort (return stream)

l.stream().sorted().forEach(arg->System.out.println(arg));

Match: Match a certain condition. anyMatch/allMatch/noneMatch (boolean is returned) exists)

boolean result = l.stream().anyMatch(arg->arg.startsWith(a));System.out.println(result);

Parallel Streams
As mentioned above, stream operations can be sequential or parallel. Sequential operations are executed in a single thread, while parallel operations are performed in multiple threads.

l.parallelStream().filter(arg->arg.startsWith(h)).map(arg->arg.toUpperCase()).forEach(arg->{ System.out.println(arg); });

It is the same as stream (), but it is more efficient.

5. Default Implementation of interfaces:
Java 8 allows the interface to have default implementation methods. The default Declaration must be added to the method:

@FunctionalInterfacepublic interface FooInterface { public default void funcA(){ System.out.println(hello java8); } public int evaluate();}

@ FunctionalInterface annotation indicates that the current interface is a function interface, that is, there must be only one abstract method. If there are multiple methods, an error is returned. Of course, the default method is not counted.

Note:
Differences between Java 8 interfaces and abstract classes:
1. abstract classes focus on inheritance and are generated for inheritance.
2. abstract classes can have constructors and member attributes. Interfaces cannot have constructors. All members are static variables and belong to Classes.
3. the default method of the Java 8 interface is compatible with lower versions. If you want to add a method after an interface is defined, the previous implementation class cannot be used and a new method must be implemented. The appearance of the default method can solve this problem. You only need to add a default method. The previous implementation class will not report an error, and the new implementation class can rewrite the default method or not rewrite it.
Refer:

http://stackoverflow.com/questions/19998454/interface-with-default-methods-vs-abstract-class-in-java-8

Want to use it in android?

Solution:
Using Lambda + Lightweight-Stream-API
Address:

https://github.com/evant/gradle-retrolambda
https://github.com/aNNiMON/Lightweight-Stream-API

Add the following content to the gradle file in the root directory:

 dependencies { classpath 'com.android.tools.build:gradle:1.3.0' classpath 'me.tatarka:gradle-retrolambda:3.2.3' }

Add the following content to the gradle file in the module directory:

apply plugin: 'me.tatarka.retrolambda'dependencies { ... compile 'com.annimon:stream:1.0.3' ...}

Add the compilation option to gradle:

android{compileOptions { sourceCompatibility 1.8 targetCompatibility 1.8 }} 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.