JAVA new features 8

Java8 new features are: the default method, functional interfaces, the lambda expression, method references, Stream , Optional , date API .

 First, the default method:

  Interface methods can have a method body , but must have a static or default modified , other methods are abstract methods , a static method can not be modified quilt interface inheritance , methods can not be overridden , only through the class name . Method name call ; a default method may be modified quilt interface inheritance , may be overwritten , invoked by calling the object's implementation class .

Second, the function interface:

  Interface and only one abstract method , generally @FuntionalInterface notes , even if it is not a function annotation interface.

Common function interface : Comparetor , Runnable.

Three, the lambda expression:

  It can be seen as a pair of anonymous inner classes abbreviated , using the interface must be a function of lambda expressions interface ;

    Note: Anonymous inner classes are compiled to produce two class files, but lambda expressions will compile produce a class file.

 

    (Parameter 1, parameter 2 ...) represents a list of parameters; -> denotes a connector; {} internal method body
    1, = type right automatically inferred from the function interface type left;
    2, if the parameter list is empty, simply reserved ();
    3, if only one parameter, () can be omitted, to name only parameter;
    4, if only one statement is executed, and no return value, {} may be omitted, if so returns value, {} to be omitted, while omitting must return, and also ensures that the statement is executed only one;
    5, the data type parameter list are automatically inferred;

    6 , the lambda local variables used in the expression of will by default be final modification , regardless of the local variable is in lamdba defined expressions or outside the defined expression. So long as the lambda used in the expression of local variables can no longer be changed, no matter what position .

 

Fourth, the method references:

    4.1 Constructor reference:

// anonymous inner classes 
PersonFacotry facotry = new new PersonFacotry () { 
  @override 
  public the Person createPerson (name String, Integer Age) { 
    // else 
    return  new new the Person (name, Age); 
  } 
}; 
// the lambda expression is written 
PersonFacotry facotry1 = (name, Age) -> new new the Person (name, Age); 

// the lambda shorthand expressions (interface functions written in this way there are several parameters, which calls the constructor corresponding to the number of parameters) 
PersonFacotry facotry2 the Person = :: new new ; 

the Person Person = facotry.createPerson (name: "XXX", Age: 100 ); 
System.out.println (Person);

    

    4.2 Static reference method

public  class the Test {
     public  static  void main (String [] args) {
         // anonymous inner classes embodiment 
        Parseinterface PIL = new new ParseInterface () { 
            @override 
            public  int the parse (String STR) {
                  return Integer.parselnt (STR); 
            } 
        }; 

         // the Lambda regular expression written 
         ParseInterface STR-PI2 => the Integer.parseInt (STR); 

        // the Lambda shorthand expression 
        ParseInterface PI3 = Integer :: the parseInt;    
    } 
}     

 

    4.3 instance method referenced

  Java1.8 provides a function interface Function , accepts two parameters

 

   Anonymous inner class way

    string str ="Hello.world";
    //匿名内部类的方式
    Function<String,Boolean> func1= new Function<String,Boolean> (){
        @override
        public Boolean apply(strinq suffix) {
             return str.endswith (suffix);
        }
    };    

 

  Lambda expressions conventional writing

// the Lambda regular expression written 
String STR = "Hello.world" ; 
Function <String, Boolean> func3 = T -> str.endsWith (T); 
System.out.println (func3.apply ( "World"));

 

  Lambda expressions shorthand

// the Lambda regular expression written 
String STR = "Hello.world" ; 
Function <String, Boolean> func2 = T -> STR :: endsWith; 
System.out.println (func2.apply ( "World"));

 

Five, Stream :

    Java 8 API adds a new abstraction called stream Stream , Stream API can greatly improve Java programmer productivity, allowing programmers to write efficient, clean, simple code .

      Note: and IO in the stream is completely different.

    In Java 8 in , set interface has two methods to generate the flow:

      Stream () - create a serial stream for the collection. ( Common )

      parallelStream () - Create a set of parallel streams.

  Stream commonly used methods:

  ForEach:

      Stream provides a new method of 'forEach' each iteration data stream. The following code fragment uses forEach output of 10 random numbers:

Random random = new Random();

random.ints().limit(10).forEach(System.out::println);

  map:

    map a method for mapping each element corresponding to a result, the following code fragment uses map output corresponding to the square of the number of elements:

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

// 获取对应的平方数 

List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

  filter:

    filter method for filtering out the conditions set by the element. The following code fragment uses filter method filtered out null string:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl"); 

// 获取空字符串的数量
int count = strings.stream().filter(string -> string.isEmpty()).count();

  limit:

    limit the method for obtaining a specified number of streams. The following code fragment uses limit the method to print out 10 pieces of data:

Random random = new Random();

random.ints().limit(10).forEach(System.out::println);

  sorted:

    sorted methods for sorting the stream. The following code fragment uses sorted method on the output 10 random numbers are sorted:

Random random = new Random();

random.ints().limit(10).sorted().forEach(System.out::println);

  Parallel ( Parallel ) Program:

    parallelStream in place of the parallel processing program stream method. The following examples we use parallelStream number to output an empty string:

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

// 获取空字符串的数量 

int count = strings.parallelStream().filter(string -> string.isEmpty()).count();

    We can easily switch directly and in parallel in order to run.

  Collectors:

Collectors class implements a number of reduction operations, for example, flow into the collection and aggregation of elements. Collectors may be used to return a list or string:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");

List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

System.out.println("筛选列表: " + filtered);

String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));

System.out.println("合并字符串: " + mergedString);

 

Six, Optional :

  Optional objects can be empty, so Optional introduction class good solution null-pointer exception .

    Be understood by the following examples Optional use of Class:

Public class User{

  private String name;

  private String password;

  ....

}

Analyzing a conventional manner:

public class Mytest{

  public static void main(String[] args){

       User user = new User();

    User.setPassword(“admin”);

    String name = getPwd(user);

    System.out.println(name);

  }

  public static String getPwd(User u){

    if(u==null){

      return “unknown”;

  }

   return u.getPassword();

}

 

Use Optional :

public static String getPwd(User u){

  return Optional.ofNullable(u)

          .map(user->user.getPassword())

          .orElse(“unknown”);

};

 

Seven, date Api :

Jdk1.8 provides us with three local date and time categories: LocalDate , LocalTime and LocalDateTime class .

When do not need to deal with time zone, using the local date and time API ( LocalDate , LocalTime and the LocalDateTime )  :

// get the current date and time 

 the LocalDateTime currentTime = LocalDateTime.now (); 

 System.out.println ( "Current Time:" + currentTime); 

the LocalDate date1 = currentTime.toLocalDate (); 

System.out.println ( "date1:" + date1); 

month month The = currentTime.getMonth (); 

int day = currentTime.getDayOfMonth (); 

int seconds The = currentTime.getSecond (); 

System.out.println ( "month:" + month + ", day:" + day + ", second:" + seconds);

 

When necessary processing time zone, date and time using the time zone of the API ( ZonedDateTime ):

ZonedDateTime dd= ZonedDateTime.now();
System.out.println(dd);
ZonedDateTime date1 = ZonedDateTime.parse(dd.toString());
System.out.println("date1: " + date1);
ZoneId id = ZoneId.of(ZoneId.SHORT_IDS.get("CTT"));
System.out.println("ZoneId: " + id);
ZoneId currentZone = ZoneId.systemDefault();
System.out.println("当期时区: " + currentZone);

 

Guess you like

Origin www.cnblogs.com/wanghj-15/p/11462056.html