java8 condensed version of the new features

A, Lambda

1. Define / design reasons

The official explanation: Allows the function as a parameter to a method. So that the code becomes more simple and compact. Expression eliminates the trouble of using anonymous methods.
Personal interpretation: to create an anonymous method

2. Structure

Lambda expressions may be a comma-separated list of parameters, -> sign statements and blocks

  • Optional type declaration: do not need to declare the parameter type, the compiler can be unified identification parameter value.
  • The optional parameters in parentheses: no need to define a parameter in parentheses, but a number of parameters need to be defined parentheses.
  • Optional braces: If the subject is only one sentence, you do not need to use braces.
  • Optional return keyword: If the subject is only one expression that returns a value, the compiler will automatically return value, braces must specify the return value

3, the rules

Local variables used in the expression or not final, will be turned into final, after the code can not change it. Global variables are not limited.

4, using


public class Java8Tester {
    @FunctionalInterface
    interface MathOperation {
        int operation(int a, int b);

    }

    @FunctionalInterface
    interface GreetingService {
        void sayMessage(String message);
    }

    public static void main(String args[]){
        //老版本写法
        MathOperation oldAdd = new MathOperation() {
            @Override
            public int operation(int a, int b) {
                return a+b;
            }
        };

        // jdk8类型声明
        MathOperation addition = (int a, int b) -> a + b;

        // 不用类型声明
        MathOperation subtraction = (a, b) -> a - b;

        // 大括号中的返回语句
        MathOperation multiplication = (int a, int b) -> { return a * b; };

        // 没有大括号及返回语句
        MathOperation division = (int a, int b) -> a / b;

        // 不用括号
        GreetingService greetService1 = message ->
                System.out.println("Hello " + message);

        // 用括号
        GreetingService greetService2 = (message) ->
                System.out.println("Hello " + message);

        greetService1.sayMessage("Runoob");
        greetService2.sayMessage("Google");
    }

}

Second, the function interface

1. Definitions

The official explanation: function interface (Functional Interface) is a one and only one abstract method, but you can have multiple non-abstract methods of the interface. Interface function can be implicitly converted to lambda expressions and method references.
@FunctionalInterface, for compiling level error checking, with the comment, when you write the interface does not meet the functional interface definition, the compiler will complain.

2, for design reasons

lambda syntax can only function interface, to facilitate the check function interface, @FunctionalInterface to this comment

3, using

@FunctionalInterfaceinterface 
GreetingService {
    void sayMessage(String message);
}
//使用Lambda表达式来表示该接口的一个实现
GreetingService greetService1 = message -> System.out.println("Hello " + message);

Third, the reference method

1. Define / design reasons

The official explanation: The name of the method to point to a method. Configuration can be made more compact and simple language, reducing redundant code.
Personal interpretation: reference method is a more concise and understandable Lambda expressions. The method of direct access or a class or instance constructor.

2, using

Create interfaces and classes

 //函数式接口
@FunctionalInterface
public interface Supplier<T> {
    T get();
}

class Car {

    public static Car create(final Supplier<Car> supplier) {
        return supplier.get();
    }

    public static void collide(final Car car) {
        System.out.println("Collided " + car.toString());
    }

    public void repair() {
        System.out.println("Repaired " + this.toString());
    }
}

Start using the reference method:

   @Test
    public void MethodReferenceTest() {
//        1、旧方法写法
//        final Car oldCar = Car.create(new Supplier<Car>() {
//            @Override
//            public Car get() {
//                return new Car();
//            }
//        });
//        2、jdk8的lambda
//        final Car oldCar1 = Car.create(() -> new Car());

        //3、jdk8写法
        //构造器引用  Class::new
        final Car newCar = Car.create(Car::new);

        //该方法返回的 List 与传入数组是映射关系(视图):set/get 操作直接作用于数组;直接修改数组,list 也会改变
        final List<Car> cars = Arrays.asList(newCar);
/*-----------------------------分割线---------------------------------------*/

//       1、旧方法写法
//        for (Car car : cars) {
//            Car.collide(car);
//        }
//        2、jdk8的forEach
//        cars.forEach(new Consumer<Car>() {
//            @Override
//            public void accept(Car car) {
//                Car.collide(car);
//            }
//        });
//        3、jdk8的lambda
//        cars.forEach(car -> Car.collide(car));

        //4、jdk8方法引用写法
        //类名的方法引用 Class::static_method 或者 Class::method
        cars.forEach(Car::collide);
/*-----------------------------分割线----------------------------------------*/

        final Car police = Car.create(Car::new);

//       1、jdk8的lambda
//        cars.forEach(car -> police.follow(car));

        //2、jdk8方法引用写法
        //特定对象的方法引用  instance::method
        cars.forEach(police::follow);
    }
 /*-----------------------------分割线---------------------------------------*/

        String[] stringsArray= {"4","5"};
//       1、旧方法写法
//        Arrays.sort(stringsArray, new Comparator<String>() {
//            @Override
//            public int compare(String s1, String s2) {
//                return s1.compareToIgnoreCase(s2);
//            }
//        });
//        2、jdk8的lambda
//        Arrays.sort(stringsArray,(s1,s2)->s1.compareToIgnoreCase(s2));

        //3、jdk8的方法引用
        Arrays.sort(stringsArray, String::compareToIgnoreCase);

Fourth, the default interface method

1. Definitions

The official explanation: The default method is the interface can be implementation, and do not need to go to achieve its implementation class method. We just in front of the method name to add a default keyword can be realized default method.

2, for design reasons

Q: Why should this feature?
A: First, before the interface is a double-edged sword, for the benefit of the abstract rather than for specific programming flaw is that when you need to modify the interface, the need to modify the entire class that implements the interface, the solution usually can think of is in the JDK Add a new approach to the relevant interface and implementation. However, the version has been released, there is no way not affect existing implementations in adding new methods to the interface at the same time. So the default method of introduction. Their purpose is to solve modify the existing implementation of the interface incompatibility problems.

3, using

(1) Interface default method
most basic use, the interface is defined by default default method, no need to implement the method implementation class

interface Vehicle {
    default void print() {
        System.out.println("我是一辆车!");
    }
}

class Car implements Vehicle{

}

If a class implements a plurality of interfaces, and these interfaces have the same default methods, you can
invoke the method specified default interface to override the default interface methods, or using super

public interface Vehicle {
   default void print(){
      System.out.println("我是一辆车!");
   }
}
public interface FourWheeler {
   default void print(){
      System.out.println("我是一辆四轮车!");
   }
}
//创建自己的默认方法,来覆盖重写接口的默认方法
public class Car implements Vehicle, FourWheeler {
   default void print(){
      System.out.println("我是一辆四轮汽车!");
   }
}
//使用 super 来调用指定接口的默认方法
public class Car implements Vehicle, FourWheeler {
   public void print(){
      Vehicle.super.print();
   }
}

(2) static default interface method
does not instantiate an interface when you can use, personal feel to lose the essence of the interface, but the compromise is so old code of friends

public interface Animal {
 static void putUpHands(){
     System.out.println("举手");
 }
}

class Cat {
    void catPutUpHands(){
        Animal.putUpHands();
    }
}

Five, Stream

1. Definitions

The official explanation: allows you to process the data in a declarative way. Element to be processed is set as a kind of stream, the flow in the pipeline transmission, and can be processed on the node conduit, such as filtering, sorting, polymerization. Elementary stream in the pipeline process after the intermediate operations, and finally to give the final result of the preceding processing operation. Stream API Java programmers can greatly improve the productivity of programmers to write efficient, clean, simple code.
Personal explained: the stream is converted into an array, and then processed by intermediate filter, map, distinct, sorted, limit or the like by .stream () or .parallelStream (), and finally through the collect, forEach, count obtain the final result.

2, for design reasons

Simplify array processing

2, using

public static void main(String[] args) {
        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
        List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5, 1, 9, 10, 4, 1);
        /*=======================返回Stream<T>==========================*/
        //1、filter过滤
        strings.stream().filter(string -> !string.isEmpty());
        //2、map映射每个元素到对应的结果
        numbers.stream().map(i -> i * i);
        //3、distinct去重
        numbers.stream().distinct();
        //4、sorted排序
        numbers.stream().sorted();
        //4、limit限制数量
        numbers.stream().limit(5);
        //5、并行处理,主要适用于大数据量的数组
        strings.parallelStream();

        /*=======================对流进行转换或处理的==========================*/
        //1、collect转换成列表或字符串,Collectors 可将流转换成集合和聚合元素
        List<String> collect = strings.stream().collect(Collectors.toList());
        String collectStr = strings.stream().collect(Collectors.joining(", "));
        //2、forEach迭代流中的每个数据
        strings.stream().forEach(System.out::println);
        //3、count统计数量
        long count = strings.stream().count();

         /*=======================拓展IntStream,LongStream,DoubleStream==========================*/

         //1.1、mapToInt将Stream转换成IntStream, summaryStatistics是对IntStream数据进行汇总统计的方法,(LongStream,DoubleStream同理)
        IntSummaryStatistics summary = numbers.stream().mapToInt(x ->x).summaryStatistics();
        System.out.println(summary.getAverage());
        System.out.println(summary.getCount());
        System.out.println(summary.getMax());
        System.out.println(summary.getMin());
        System.out.println(summary.getSum());

        //1.2、IntStream,LongStream创建区间方式是一样的
        int[] range1 = IntStream.rangeClosed(13, 15).toArray();//生产区间 [a,b]      range1=[13,14,15]
        int[] range2 = IntStream.range(13, 15).toArray();//生产区间 [a,b)     range2=[13,14]
        double[] doubles = DoubleStream.of(5.33, 2.34, 5.32, 2.31, 3.51).toArray(); //doubles=[5.33, 2.34, 5.32, 2.31, 3.51]

        //1.2、IntStream的统计方法(LongStream,DoubleStream同理)
        double average = IntStream.range(13, 15).average().getAsDouble();//average=13.5
        int max = IntStream.range(13, 15).max().getAsInt(); //max=14
        int min = IntStream.range(13, 15).min().getAsInt(); //min=13
        int sum = IntStream.range(13, 15).sum(); //sum=27
    }

Six, Optional category

1. Definitions

The official explanation: Optional class is a container object can be null. If the value exists isPresent () method returns true, call the get () method returns the object. Optional is container: it can hold the value of type T, or just to save null.

Personal explanation: in other words converted into a variable Optional objects, which are converted into null Optional.empty () (Optional is an empty object), then the object can operate on Optional. Benefit is found null alternative thrown.

2, for design reasons

Without explicitly for null detection. Solve null pointer exception. Avoid null.

3, using

public class OptionalTest {
    public static void main(String args[]){
        handleParam(null,1);//后面两个参数自己随意写

    }
    //处理参数举例子
    static void handleParam(String a,Integer b){
        //对于处理string参数
        Optional<String> aOpt = Optional.ofNullable(a); //允许参数空。如果非空返回一个包含引用Optional实例,否则返回Optional.empty()。
        System.out.println(aOpt.isPresent());//输出aOpt是否为空
        a=aOpt.orElse("defaultValue");//如果为空,就给一个默认值defaultValue
        System.out.println(a);

        //同理对于处理int参数
        Optional<Integer> bOpt = Optional.of(b);//不允许参数空,不然会抛出异常
        b=bOpt.get();//get的时候不允许变量为空
        System.out.println(b);
    }
}

Sixth, the date and time of the class

1. Definitions

To strengthen the handling of date and time.

2, for design reasons

In older versions of Java, there are many problems date and time API

  • (1) non-thread-safe - java.util.Date non-thread-safe, all the dates are variable class, which is one of the biggest problems date Java classes.
  • (2) poor design - defined Java date / time is not the same class, and in java.util package java.sql class includes the date, in addition to formatting and parsing the class definition package java.text .
    java.util.Date contains the date and time, and contains only java.sql.Date date will be incorporated into the package java.sql unreasonable. In addition these two classes have the same name, which itself is a very bad design.
  • (3) time zone handling trouble - Date class does not offer international, no time zone support, so the introduction of Java and java.util.TimeZone java.util.Calendar class, but they are all above problems also exist.

3, using

 public static void testTime() {

        // 当前详细时间
        LocalDateTime currentTime = LocalDateTime.now(); //currentTime =  2019-05-30T15:05:46.408
        // 当前年月日
        LocalDate date1 = currentTime.toLocalDate(); //date1 = 2019-05-30

        //获取详细时间的月日秒
        Month month = currentTime.getMonth();//month=MAY
        int day = currentTime.getDayOfMonth();//day=30
        int seconds = currentTime.getSecond();//seconds=46

        //替换详细时间的年月
        LocalDateTime date2 = currentTime.withDayOfMonth(10).withYear(2012);//date2 = 2012-05-10T15:05:46.408

        //自定义年月日
        LocalDate date3 = LocalDate.of(2014, Month.DECEMBER, 12);//date3= 2014-12-12

        //自定义时分
        LocalTime date4 = LocalTime.of(22, 15); //date4 = 22:15

        //解析字符串
        LocalTime date5 = LocalTime.parse("20:15:30"); //date5 = 20:15:30
        LocalDateTime date6 = LocalDateTime.parse("2019-05-30T15:05:46.408");//date6 = 2019-05-30T15:05:46.408

        // 获取当前时间日期
        ZonedDateTime date7 = ZonedDateTime.parse("2015-12-03T10:15:30+05:30[Asia/Shanghai]");//date6=2015-12-03T10:15:30+08:00[Asia/Shanghai]
        // 获取时区ID
        ZoneId id = ZoneId.of("Europe/Paris");//id= Europe/Paris
        //获取默认时区
        ZoneId defaultZone = ZoneId.systemDefault();//defaultZone=sia/Shanghai
    }

Seven, Base64

1. Definitions

Official explanation: the Base64 tools provides a method to obtain the following three static BASE64 encoder and decoder:

  • Basic: output is mapped to a set of characters A-Za-z0-9 + /, do not add any line coding standard, decoded output only supports A-Za-z0-9 + /.
  • URL: output mapping to a set of characters A-Za-z0-9 + _, URL and the file is output.
  • MIME: MIME-friendly format output hidden strikes. Each output line is not more than 76 characters, and '\ r' and follow the '\ n' as the split. Encoding the output of the last row is not divided.

2, using

public static void main(String args[]) {
       try {

           // 使用基本编码
           String base64encodedString = Base64.getEncoder().encodeToString("我是测试字符串".getBytes("utf-8"));//base64encodedString = "5oiR5piv5rWL6K+V5a2X56ym5Liy"

           // 解码
           byte[] base64decodedBytes = Base64.getDecoder().decode(base64encodedString);
           String base64decodedStr= new String(base64decodedBytes, "utf-8");//base64decodedStr = "我是测试字符串"

           //使用URL编码
           String urlEncodedString = Base64.getUrlEncoder().encodeToString("testUrl?java8".getBytes("utf-8"));//urlEncodedString = "VHV0b3JpYWxzUG9pbnQ_amF2YTg="

           //使用MIME编码
           String mimeEncodedString = Base64.getMimeEncoder().encodeToString(("QWERTYUIOP-ASDFGHJKL-ZXCVBNM").getBytes("utf-8"));//mimeEncodedString = "UVdFUlRZVUlPUC1BU0RGR0hKS0wtWlhDVkJOTQ=="

       }catch(UnsupportedEncodingException e){
           System.out.println("Error :" + e.getMessage());
       }
   }

Guess you like

Origin blog.csdn.net/xunjiushi9717/article/details/91452003